简体   繁体   中英

Which is more efficient Object class casting or Double.parseDouble(String)

A block of code similar to this sparked some debate on to which part of the code was most efficient or if there was a more correct way to do this. One argument was that the cast was more efficient than creating a string to parse. One argument was that the multiple class casts was creating more objects than creating the string to parse.

What is the "best practice"?

Object some_num_obj;
double some_num;
if(some_num_obj instanceof Integer)
{
    some_num = (double) (int) (Integer) some_num_obj;
}
else if(some_num_obj instanceof Double)
{
    some_num = (Double) some_num_obj;
}
else
{
     some_num = Double.parseDouble(some_num_obj.toString());
}

The most efficient and possibly the fastest is to use Number.doubleValue and Double.parseDouble

if(some_num_obj instanceof Number)
    some_num = ((Number) some_num_obj).doubleValue();
else
    some_name = Double.parseDouble(some_num_obj.toString());

The best practice is the one that is the most readable. Unless that piece of code is ran tens of thousands of times in a row, the efficiency difference is as good as non-existing.

Not really sure whether it's applicable in your application, you might want to take a look at the java.lang.Number class as a method parameter.

One argument was that the multiple class casts was creating more objects

Wrong. Class casts don't create any objects.

Types are nothing more than a way of telling the compiler what to do with a variable, they do not create new objects. Both creating a string from a number and parsing the string back into a number are quite expensive. The only potential trouble with casting is type-safety, which you take care of with the instanceof.

As a sidenote, the extra cast to double in the first part is extraneous.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM