我不时看到这样的代码:
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优化
发布评论