最有效的方法是将一个盒装双倍乘以2? [英] Most efficient way to multiply a boxed double by 2?
问题描述
foo
,我们要将其值乘以 2
并存储它在另一个盒装双变量 bar
中。从以下方法, 方法一:
Double bar = foo * 2;
和
二:
Double bar = Double.valueOf(foo.doubleValue()* 2);
哪个更适合考虑效率,可读性等?或者这些方法实际上相当的差别呢?
第一个。它具有更好的可读性,并在场景后面保持所有的拳击/拆箱操作。
不要考虑这样简单的操作的效率,如乘以2
...或长回答
有两种方法:
void method1(){
Double foo = 1.0;
Double bar = foo * 2;
}
void method2(){
Double foo = 1.0;
Double bar = Double.valueOf(foo.doubleValue()* 2);
}
编译 javac
并查看 javap
void method1();
代码:
0:dconst_1
1:invokestatic#2 //方法java / lang / Double.valueOf:(D)Ljava / lang / Double;
4:astore_1
5:aload_1
6:invokevirtual#3 //方法java / lang / Double.doubleValue :()D
9:ldc2_w#4 // double 2.0 #2 //方法java / lang / Double.valueOf:(D)Ljava / lang / Double; d
12:dmul
13:invokestatic#
16:astore_2
17:return
void method2();
代码:
0:dconst_1
1:invokestatic#2 //方法java / lang / Double.valueOf:(D)Ljava / lang / Double;
4:astore_1
5:aload_1
6:invokevirtual#3 //方法java / lang / Double.doubleValue :()D
9:ldc2_w#4 // double 2.0 #2 //方法java / lang / Double.valueOf:(D)Ljava / lang / Double; d
12:dmul
13:invokestatic#
16:astore_2
17:return
你能发现差异吗? / p>
Let's say we have a boxed double variable, foo
and we want to multiply its value by 2
and store it in another boxed double variable , bar
. From the following approaches,
Approach One:
Double bar = foo * 2;
and,
Approach Two:
Double bar = Double.valueOf(foo.doubleValue() * 2);
which one is more preferable considering efficiency, readability, and etc.? Or is the difference so trivial that these approaches are practically equivalent?
First one. It has better readability and keep all boxing/unboxing operations behind the scene.
Do not think about efficiency of such simple operation as multiplying by 2.
...or long answer
Have two methods:
void method1() {
Double foo = 1.0;
Double bar = foo * 2;
}
void method2() {
Double foo = 1.0;
Double bar = Double.valueOf(foo.doubleValue() * 2);
}
Compile with javac
and look bytecode instructions with javap
void method1();
Code:
0: dconst_1
1: invokestatic #2 // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
4: astore_1
5: aload_1
6: invokevirtual #3 // Method java/lang/Double.doubleValue:()D
9: ldc2_w #4 // double 2.0d
12: dmul
13: invokestatic #2 // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
16: astore_2
17: return
void method2();
Code:
0: dconst_1
1: invokestatic #2 // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
4: astore_1
5: aload_1
6: invokevirtual #3 // Method java/lang/Double.doubleValue:()D
9: ldc2_w #4 // double 2.0d
12: dmul
13: invokestatic #2 // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
16: astore_2
17: return
Can you spot the difference?
这篇关于最有效的方法是将一个盒装双倍乘以2?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!