September 21, 2001
Having seen your answer on parsing ints in "Help With Ints," it bought to mind an issue I came upon while performance tuning our Java application.
Getting a double from a string involves using:
Double.valueOf(aString).doublevalue();
This method has the overhead of creating an immediately-thrown-away Double object.
Looking at the Double class source code, you see that a new Double is instantiated:
public static Double valueOf(String s) throws NumberFormatException
{
return new Double(valueOf0(s));
}
This leads to two questions:
Integer.parseInt() that returns the double value without the extraneous Double creation?valueOf() method?
Prior to Java 2's release, it was true that the Double API lacked a way to parse a string without the creation of extraneous
Double objects. Here's a pointer to the old Double documentation.
Why didn't Sun include a leaner method in the API? Your guess is as good as mine. If anyone does know, please tell me and I can pass the information along.
You'll be happy to know that Sun added a parseDouble() method to the Double API as of Java 1.2. The static parseDouble() method parses a double string directly into its double value. Take a look through the source code if you want to see exactly
how the string gets parsed. The source is available from Sun for download. I'd post the pertinent code here, but I'm not a copyright lawyer, and Sun has better
lawyers than I do.
If you do look at the source code, you will note that the parsing of a double string is not as direct as the parsing of an
integer string. An intermediary object is created when parsing double strings. However, this same intermediary object gets
instantiated if you call valueOf() yourself. So you still do save the cost of the extra Double instantiation by calling parseDouble() instead of valueOf().
Double documentation, see "Class java.lang.Double" on java.sun.comDouble, go to