Java Performance Tuning with maximizing Integer.valueOf(int)
or auto boxing(uses internal a valueOf too) the cached Integer values will be used if they are between -127 and +128.
Now I found coincidentally(by looking at the source) on a Java feature or more exactly on a property. With that property you can tune the maximum of the internal Integer cache.
The Properties is called ‘java.lang.Integer.IntegerCache.high’. For each number in the range a Integer value will be created at the beginning of using Integer (it’s initialized in a static).
The feature is only available since some JDK Update versions (I don’t know exactly which).
So you have to ask yourself, can you benefit from a higher cache or are the numbers normally not used?
You save the following memory, if the number is in you cache:
- the numeric value and its architecture padding (e.g. int needs 8 bytes on 64bit architecture, if there are no other primitive numbers to combine it with)
- the header of an object, which is 2xWORD. On 32bit 2×4 bytes, on 64bit, 2×8 bytes.
Always use Integer.valueOf. “new Integer” is obsolete.
Do you need numbers higher than 128 often in the application? Is it worth creating the overhead for each Integer between -127 and your max number?
If a value is mandatory you should use a primitive int value, because the value is saved directly with no reference and object overhead.
More details on the memory usage.