views:

55

answers:

4

Why YOU should use Integer.valueOf(int)

In particular, why you should use Integer.valueOf(int) instead of new Integer(int): CACHING.

But in JDK 5+, you should really use valueOf because Integer now caches Integer objects between -128 and 127 and can hand you back the same exact Integer(0) object every time instead of wasting an object construction on a brand new identical Integer object.

How can extend the range ?

regards Trus

+1  A: 

How can extend the range ?

Implement your own analog of the Integer.valueOf(int) method with a bigger (static) cache array. Then change your application code to use that method instead of the standard one.

However, as other answers have pointed out, this won't necessarily make your application run faster, or use less memory.

  1. The larger cache array will occupy more memory.
  2. Integer objects in the cache will always be reachable, and therefore they won't be garbage collected.
  3. Having more reachable Integer objects will make GC runs take longer.
Stephen C
Why the downvote?
Stephen C
+1  A: 

My questions to you are:

1) Why is your code making new Integer objects hurting you? Do you have a profile result to share, to prove that making too many Integers is slowing your down? Object pooling, in general, is a BAD idea. You need a good case to justify it.

2) Why are you doing new Integer(int)? If you just keep it as a primitive int, not only will you avoid "creating a new object". you will not create any object at all. Auto boxing will handle converting it to an Integer if you need it at a later point in time.

*Disclaimer I Don't use EITHER.. I write performance sensitive code, but have never come to a point where I would manually turn a primitive int into an Integer. I just keep as an int whenever possible, and let the JVM autobox if it is needed.

bwawok
Although you don't specifically answer the OP's question, I 100% agree with you here. Pooling such "cheap" Objects is almost certainly a bad idea.
Waldheinz
+1  A: 

Extending the range of the cache may not get you what you are wanting, but if you have a real need to cache a greater range, you can use this code instead of Integer.valueOf(int). You just need to adjust the cache range values to the range you want.

private static class IntegerCache 
{
    private IntegerCache(){}

    static final Integer cache[] = new Integer[-(-128) + 127 + 1];

    static 
    {
        for(int i = 0; i < cache.length; i++)
        cache[i] = new Integer(i - 128); 
    }
}

public static Integer valueOf(int i) 
{
    final int offset = 128;
    if (i >= -128 && i <= 127) // must cache 
    {
        return IntegerCache.cache[i + offset];
    }
    return new Integer(i);
}

The code is from: http://www.owasp.org/index.php/Java_gotchas

Alan Geleynse
+1  A: 

You can use the java.lang.Integer.IntegerCache.high property to increase the size of this cache.
ex :

java -Djava.lang.Integer.IntegerCache.high=4096 SomeClass.class
Daniel Teply