java optimization by compiler or JIT

倖福魔咒の 提交于 2019-12-10 16:00:35

问题


From time to time I see code like this:

if (id.split(":").length > 1) {
 sub_id = id.split(":")[1];
 parent_id = id.split(":")[0];
}

Wouldn't it be better (and faster) to do something like

String [] ids = id.split(":");
if (ids.length > 1) {
  sub_id = ids[1];
  parent_id = ids[0];
}

This way you don't have to call 'split()' multiple times, or will the compiler/JIT do such optimizations?


回答1:


I certainly wouldn't expect either the JIT or the compiler do perform such optimizations. It would have to know that:

  • The results don't "usefully" change between calls
  • Nothing was going to use the fact that each method call produces separate arrays
  • Nothing was going to use the fact that each method call produces different string objects

It seems very unlikely that either the JIT or the compiler would optimize for this.

Yes, it's definitely more efficient to use the second form - and I'd argue it's more readable too. When more readable code is also more efficient, that's a pretty clear indication of which code to use ;)



来源:https://stackoverflow.com/questions/15339510/java-optimization-by-compiler-or-jit

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