4

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?

2
  • The optimization engine can improve performance of the algorithm used, but cannot (to my knowledge) replace your code with another algorithm. Commented Mar 11, 2013 at 13:21
  • 1
    If this is not just a theoretical question, but you have a real need to optimize the code, I would avoid to use the regexp-able split method at all. Using indexOf to find the ':' and two substring calls to extract each part of the id ought to be much faster than both alternatives. Commented Mar 11, 2013 at 14:00

1 Answer 1

10

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

Sign up to request clarification or add additional context in comments.

14 Comments

Measure first, then you have hard data instead of waving your arms.
... I sometimes get the impression that people expect the compiler to be smarter than it is.
@OddBeck: Why didn't you test the actual code you presented? Surely that would be simpler and more useful.
@jarnbjo: That would be surprising - and very easily observed, just by comparing references. Would love to see evidence that it's happening though.
@jarnbjo: Right, but it's also possible because the results really, really can't be distinguished from each other. That's not true with String.split.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.