Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 316
user321605 Avatar asked Aug 02 '11 03:08

user321605


2 Answers

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.

like image 131
Oscar Gomez Avatar answered Nov 05 '22 19:11

Oscar Gomez


A major difference between using a single-element array versus autoboxing is that the array will be mutable, which may in some cases be good and in other cases bad. Having the array mutable will improve performance in cases where it is safe to reuse the same array to pass different variables to methods which are going to read out the array's contents but not keep any reference to it. It may, however, lead to a variety of hard-to-find bugs if code keeps a reference to one of the arrays for the purpose of persisting its value, and some other code changes the value stored in the array.

like image 34
supercat Avatar answered Nov 05 '22 20:11

supercat