Map.get() optimization in ?: ternary operator

半世苍凉 提交于 2019-12-02 02:18:53

问题


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";

) ?


回答1:


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.




回答2:


Your second option which is :

String value = map.get(key);
if(value == null) {
    value = "DEFAULT_VALUE";
}

is better from first one reason:

  1. You dont create an extra reference "tmp"

  2. You dont execute else which you do as part of your ternary comparison.




回答3:


The IF one is preferable.

Its more readable & self explained.

Additionally: execution time is not a big deal, at least here.



来源:https://stackoverflow.com/questions/8506303/map-get-optimization-in-ternary-operator

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!