???(?)优化??:三元运算符 [英] Map.get() optimization in ?: ternary operator
问题描述
考虑以下代码:
java.util.Map< String,String> map = new java.util.HashMap< String,String>();
...
String key =A;
String value = map.get(key)== null? DEFAULT_VALUE:map.get(key); //(1)
将编译器优化行(1)
类似于
String tmp = map.get(key) ;
字符串值= tmp == null? DEFAULT_VALUE:tmp;
(或到:
String value = map.get(key);
if(value == null)value =DEFAULT_VALUE;
)
?
不知道如果你问这对应于编译器将对原始表达式做出什么,在这种情况下,答案是:
两者 -
在这个例子中,你调用了map.get()两次;编译器不知道没有副作用,所以当找到一个值时它会调用它两次。
可能最接近
String tmp = map.get(key);
字符串值;
if(tmp == null)
value =DEFAULT_VALUE;
else
value = map.get(key);
或者如果你问哪个替代方案是最有效的,那么答案是:
第二个选择可能稍微好一些,因为它不需要额外的局部变量。一个额外的本地变量在JVM上施加轻微的开销,但是在JIT通过它之后,它可能在运行时无关紧要。
Consider the following code:
java.util.Map<String, String> map = new java.util.HashMap<String, String>();
...
String key = "A";
String value = map.get(key) == null? "DEFAULT_VALUE" : map.get(key); // (1)
Would the compiler optimize the line (1)
something similar to:
String tmp = map.get(key);
String value = tmp == null? "DEFAULT_VALUE" : tmp;
(or to:
String value = map.get(key);
if(value == null) value = "DEFAULT_VALUE";
) ?
Not sure if you are asking which corresponds to what the compiler will make of the original expression, in which case the answer is:
Neither--
In the example you are calling map.get() twice; the compiler can't know that there are no side effects, so it will call it twice when a value is found.
Probably closest to
String tmp = map.get(key);
String value;
if (tmp == null)
value= "DEFAULT_VALUE";
else
value = map.get(key);
Or if you are asking which alternative is most efficient, in which case the answer is:
The second alternative is probably slightly better because it does not require an additional local variable. An additional local variable imposes a slight overhead on the JVM, but it will probably amount to nothing at runtime once the JIT gets through with it.
这篇关于???(?)优化??:三元运算符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!