Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java optimization by compiler or JIT

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?

like image 618
OddBeck Avatar asked Dec 26 '22 07:12

OddBeck


1 Answers

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

like image 156
Jon Skeet Avatar answered Jan 11 '23 11:01

Jon Skeet