Difference between Long.valueOf(java.lang.String) and new Long(java.lang.String)?

拜拜、爱过 提交于 2019-11-29 23:59:20

The difference is that using new Long() you will always create a new object, while using Long.valueOf(), may return you the cached value of long if the value is between [-128 to 127].

So, you should prefer Long.valueOf method, because it may save you some memory.

If you see the source code for Long.valueOf(String), it internally invokes Long.valueOf(long), whose source code I have posted below: -

public static Long valueOf(String s) throws NumberFormatException
{
    return Long.valueOf(parseLong(s, 10));
}

public static Long valueOf(long l) {
    final int offset = 128;
    if (l >= -128 && l <= 127) { // will cache 
        return LongCache.cache[(int)l + offset];
    }
    return new Long(l);
}

Long.valueOf() should be preferred: it returns cached values of Long for some often-used values instead of constructing a new instance as the constructor does.

Even if some Java versions don't use a cache, using valueOf() makes it possible in future versions, whereas the constructor will always create a new instance.

They mean the same

public static Long valueOf(String s) throws NumberFormatException{
        return new Long(parseLong(s, 10));
}

public Long(String s) throws NumberFormatException {
    this.value = parseLong(s, 10);
}

Source JDK 6.0

Both do parseLong(String, int) internally (int being radix with value as 10), but valueOf has advantage as documented below:

If a new Long instance is not required, this method should generally be used in preference to the constructor Long(long), as this method is likely to yield significantly better space and time performance by caching frequently requested values.

This is the PMD plugin out put which is run on eclipse

Code I checked is

Long l = new Long("123456");

In JDK 1.5, calling new Long() causes memory allocation. Long.valueOf() is more memory friendly.

i am thinking how to change range and size of the cache for our application, overloaded with Longs;

such change is not supported by j2se api One way is to change loaded java byte code with ClassLoader or even with JVMTI (it allows to keep such trick out of the project, like external tuning)

or, may be, to create external cache and own static cachedValueOf() which is straight forward, but the code depending on some not applicational needs is not nice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!