[infinispan-dev] writeUnsignedInt() inefficient with bytes between 128 and 255

Galder Zamarreno galder.zamarreno at redhat.com
Thu Sep 3 06:53:25 EDT 2009


Hi,

While looking at https://jira.jboss.org/jira/browse/ISPN-149, I've 
realised that writeUnsignedInt(), due to its dynamic behaivour, it's 
more efficient than using a leading byte and then writing a byte, short 
or int.

However, I've spotted an unefficiency in 
UnsignedNumeric.writeUnsignedInt() which is that if you write a byte 
that's between 128-255, it writes two bytes, whereas in theory, you 
could just write it as a single unsigned byte.

Now, I'm not an expert on these methods, but I believe a 
writeUnsignedInt like this would make 128-255 bytes be written as 1 byte 
too:

    public static void writeUnsignedInt(ObjectOutput out, int i) throws 
IOException {
       while ((i & ~0xFF) != 0) {
          out.writeByte((byte) ((i & 0xFF) | 0x100));
          i >>>= 8;
       }
       out.writeByte((byte) i);
    }

And the read part would look like:

    public static int readUnsignedInt(ObjectInput in) throws IOException {
       int b = in.readUnsignedByte();
       int i = b & 0xFF;
       for (int shift = 8; (b & 0x100) != 0; shift += 8) {
          b = in.readUnsignedByte();
          i |= (b & 0xFFL) << shift;
       }
       return i;
    }

Manik, I think you created these methods in the 1st place, thoughts? 
CC'ing David M L who's quite an expert on this too.

Cheers,
-- 
Galder Zamarreño
Sr. Software Engineer
Infinispan, JBoss Cache



More information about the infinispan-dev mailing list