What is the difference between calling Double.valueOf (String s) and the new Double (String s)?

So, I have a String, and I want to create a Double object with a string as a value.

I can call

Double myDouble = new Double (myString);

or i can call

Double myDouble = Double.valueOf(myString);

Is there any difference? I assume that the first guarantees the creation of a new object on the heap, and the second can reuse an existing object.

For extra credit : the string may be null, in which case I want Double to be null, but both above have thrown a NullPointerException. Is there any way to write

Double myDouble = myString == null ? null : Double.valueOf(myString);

less code?

+9
java
source share
6 answers

Depends on the implementation. openJDK 6 b14 uses this implementation of Double(String s) :

 this(valueOf(s).doubleValue()); 

Thus, it calls valueOf(String s) internally and should be less efficient than calling this method directly.

+3
source share

Your guess is correct. The second way to get Double Out of String can be faster, because the value can be returned from the cache.

As for the second question, you can create a helper null safe method that returns null instead of throw NullPointerException.

+3
source share

from apache

 public static Double valueOf(String string) throws NumberFormatException { return new Double(parseDouble(string)); } 

&

 public Double(String string) throws NumberFormatException { this(parseDouble(string)); } 

from the sun [oracle] jdk

  public Double(String s) throws NumberFormatException { // REMIND: this is inefficient this(valueOf(s).doubleValue()); } 

&

 public static Double valueOf(double d) { return new Double(d); } 
+3
source share

No difference, at least in Oracle JDK 1.6:

 public Double(String s) throws NumberFormatException { // REMIND: this is inefficient this(valueOf(s).doubleValue()); } 
+2
source share

If you are concerned about performance, you should use a primitive.

 double myDouble = Double.parseDouble(myString); 
0
source share

this will either return a valid Double, or null otherwise.

 Double myDouble = null; try { myDouble = Double.valueOf(myString); } catch (Exception e) { } 

it processes even when myString is null

0
source share

Source: https://habr.com/ru/post/651343/


All Articles