Search code examples
javainterfaceboxingautoboxingunboxing

Avoiding boxing by passing in single element primitive array


I'm working with an interface that takes type Object as its input. This is unfortunate for me as I have primitive data that I sometimes need to pass in through the interface. This of course forces me to box.

Profiling has shown this area to be a hotspot in the code. I am thus exploring alternatives to make this area faster.

An idea I had today for this is to preallocate a static primitive array, and to store the primitive value in this, and then pass the array through (and then in the implementation of the interface, grab the double out of the array.

I have written some code in effort to test this. For reasonably high values (10 million), I am seeing that the array method is SIGNIFICANTLY faster. As I increase the number of iterations of my test, the two converge.

I'm wondering if anyone has thought about this approach before, and if there are any suggestions on how to benchmark this well.

Example Code:

Double data = Double.valueOf(VALUE);
inst.interface(data);
//inside interface(Object object)...
Double data = (Double) object;
double d = data.value();

vs...

doublearray[0] = VALUE;
inst.interface(data);
//inside interface(Object object)...
double[] data = (double[]) object;
double d = data[0];

Thanks! RB


Solution

  • I would go with the array option, as only one object is allocated ever (the array), versus the number of times you would have to allocate one in the autoboxing, even though valueOf() is optimized for some values.