通过编译器或JIT进行Java优化 [英] java optimization by compiler or JIT

查看:75
本文介绍了通过编译器或JIT进行Java优化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不时看到这样的代码:

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];
}

这样,您不必多次调用'split()' ,还是编译器/ JIT会做这样的优化?

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

推荐答案

我当然不会期望这两者 JIT 编译器会执行此类优化。必须知道:

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


  • 结果在两次调用之间不会有用地改变

  • 什么都不会使用每个方法调用会生成单独的数组的事实

  • 什么都不会使用每个方法调用会生成不同的字符串对象的事实

JIT或编译器似乎都不大可能对此进行优化。

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

这篇关于通过编译器或JIT进行Java优化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆