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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With