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

后端 未结 6 457
萌比男神i
萌比男神i 2020-12-24 13:13

I\'m consolidating code written by two different people and notice that casting a String value into a Long has been done in two different ways.

Coder #1 has done t

6条回答
  •  时光说笑
    2020-12-24 13:52

    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);
    }
    

提交回复
热议问题