问题
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