What is the most preferred way of converting a String
to Long
(the Object) in Java.
Long a = new Long(str);
OR
Long a = Long.parseLong(str);
Is there a correct way here because both seem to have the same level of readability and is it acceptable to add an extra step of autoboxing
in the first method?
Have a close look at the return types:
Long.parseLong(String)
returns a primitive long
, so there will be re-boxing in this case: Long a = Long.parseLong(str);
.new Long(String)
will create a new Long
object in every case. So, don't do this, but go for 3)Long.valueOf(String)
returns a Long
object, and will return cached instances for certain values -- so if you require a Long
this is the preferred variant.Inspecting the java.lang.Long
source, the cache contains the following values (Sun JDK 1.8):
private static class LongCache {
private LongCache(){}
static final Long cache[] = new Long[-(-128) + 127 + 1];
static {
for(int i = 0; i < cache.length; i++)
cache[i] = new Long(i - 128);
}
}
The best approach is Long.valueOf(str)
as it relies on Long.valueOf(long)
which uses an internal cache making it more efficient since it will reuse if needed the cached instances of Long
going from -128
to 127
included.
Returns a
Long
instance representing the specified long value. If a new Long instance is not required, this method should generally be used in preference to the constructorLong(long)
, as this method is likely to yield significantly better space and time performance by caching frequently requested values. Note that unlike the corresponding method in the Integer class, this method is not required to cache values within a particular range.
Generally speaking, it is a good practice to use the static
factory method valueOf(str)
of a wrapper class like Integer
, Boolean
, Long
, ... since most of them reuse instances whenever it is possible making them potentially more efficient in term of memory footprint than the corresponding parse
methods or constructors.
Excerpt from Effective Java Item 1
written by Joshua Bloch:
You can often avoid creating unnecessary objects by using static factory methods (Item 1) in preference to constructors on immutable classes that provide both. For example, the static factory method
Boolean.valueOf(String)
is almost always preferable to the constructorBoolean(String)
. The constructor creates a new object each time it’s called, while the static factory method is never required to do so and won’t in practice.
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