Avoiding boxing by passing in single element primitive array
Asked Answered
A

2

10

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

Abroach answered 2/8, 2011 at 3:7 Comment(1)
why not have a global double variable then?Bisector
P
1

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.

Plum answered 2/8, 2011 at 3:16 Comment(1)
My tests show the array technique to be an order of magnitude faster! I suspected it would be at least competitive, but this was much more than I expected.Abroach
L
1

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.

Loren answered 7/2, 2014 at 21:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.