2011-02-10 13 views
3

我想问一些关于我的算法的一部分的意见/建议。投射原始字体与修剪字节的方式

ByteBuffer bb = ByteBuffer.allocate(8); 
bb.putLong(rs.getLong(index));//retrieve long from db (unsigned INT) 
byte[] tmp = new byte[4]; 
bb.position(4); 
bb.get(tmp); 
(Inet4Address) InetAddress.getByAddress(tmp); 

ByteBuffer bb = ByteBuffer.allocate(4); 
bb.putInt((int) rs.getLong(index));//retrieve long from db (unsigned INT) 
bb.flip(); 
byte[] tmp = new byte[4]; 
bb.get(tmp); 
(Inet4Address) InetAddress.getByAddress(tmp); 

基本上,我想知道是否有铸造性能差或者是它更好地使用更大的ByteBuffer。

感谢,问候,

马立克

+4

将这两个块封装在方法中,编写几个测试并比较性能。为什么依靠其他人的意见,当你可以有确切的结果? – 2011-02-10 14:07:41

回答

3

基本上,我想知道是否有铸造性能差或者是它更好地使用更大的ByteBuffer。特别是相对于分配新ByteBuffer S和调用一些方法

铸造是“便宜”。

我不完全确定你想要做什么,但也许一个简单的右移会做诡计?例如这段代码:

long l = rs.getLong(index); 
InetAddress.getByAddress(new byte[] { (byte) ((l & 0xFF000000) >> 24), 
             (byte) ((l & 0x00FF0000) >> 16), 
             (byte) ((l & 0x0000FF00) >> 8), 
             (byte) ((l & 0x000000FF) >> 0)}); 
+0

+1 - 从性能的角度来看,创建和使用`ByteBuffer`来将`int`变成`byte [4]`是非常可怕的。 – 2011-02-10 14:19:15