Tuesday, April 10, 2012

Converting a byte array to long - a performance test

WARNING: Micro benchmarks are mostly deceiving, if you aren't careful about how to interpret the results. I leave it up to you to interpret these results.

Recently I came across a problem when I had to convert an array of bytes into a long value. The obvious choice was for me to write a bytesToLong method that takes a byte array as an argument and returns a long value. When I dug around a little bit, I found that I could also make use of the ByteBuffer to wrap the bytes and  make use of the getLong() method to get the long value.

I was curious to know if there is any performance benefits of going one way or the other. So I wrote a small micro benchmark, and here is the source code and the results:

The results are given below:
The columns are: number of iterations, time taken by the shift version, time taken by the ByteBuffer version, the ratio between the two times. As you can see, the ByteBuffer version is four times slower than the hand coded version. For my case, this slowness doesn't make any difference. But depending on your application, it may be significant.

1 comment:

Amil said...

Thank you for this. I decided against using ByteBuffer for efficiency (both speed and code bloat from an extra import and library loading, etc., etc.).