2011-02-10 14 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