简体   繁体   English

这是更有效的Object类转换或Double.parseDouble(String)

[英]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 最有效,可能最快的方法是使用Number.doubleValue和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. 不太确定它是否适用于您的应用程序,您可能想看一下java.lang.Number类作为方法参数。

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. 强制转换的唯一潜在麻烦是类型安全,您可以使用instanceof来解决。

As a sidenote, the extra cast to double in the first part is extraneous. 附带说明一下,在第一部分中增加一倍的额外演员是多余的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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