Double trouble

What's the best way to return doubles without affecting performance?

September 21, 2001

Q: 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:

  1. Why didn't Sun provide an equivalent method to Integer.parseInt() that returns the double value without the extraneous Double creation?
  2. Can I add a method to one of my classes that returns the double value by accessing the valueOf() method?

A: 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().

Tony Sintes is an independent consultant and founder of First Class Consulting, Inc., a consulting firm that specializes in the bridging of disparate enterprise systems and training. Outside of First Class Consulting, Tony is an active freelance writer as well as author of Sams Teach Yourself Object-Oriented Programming in 21 Days (Sams, 2001; ISBN: 0672321092).

Learn more about this topic