1

I was looking at John's answers here and thought it was pretty slick. I was wondering if it could be improved further with an if statement, but I'm not sure if an if statement would perform better or not.

Does an if statement "cost more" than changing the value of a String?

String prefix = "";
for (String serverId : serverIds) {
  sb.append(prefix);
  prefix = ",";
  sb.append(serverId);
}

VS.

String prefix = "";
for (String serverId : serverIds) {
  sb.append(prefix);
  if( prefix.equals( "" ) {
      prefix = ",";
  }
  sb.append(serverId);
}
8
  • 4
    You're not mutating a String, you're changing a reference variable. (At any rate, Strings are immutable!) Commented Jan 3, 2013 at 20:57
  • 5
    Also, if this is important, then you should probably profile it. Commented Jan 3, 2013 at 20:57
  • If this is important, I'd like to know why. Commented Jan 3, 2013 at 20:58
  • 4
    I still say that using Joiner in Guava would be better :) Commented Jan 3, 2013 at 20:58
  • 4
    By writing this question, you have probably spent more time than such an optimization would save, even if your program were run billions upon billions of times. Commented Jan 3, 2013 at 21:08

2 Answers 2

2

The second version would be definitively slower. It is not just an if, but also an equals call, and most of the time the two compared strings will be different, therefore the equals method will not return early - instead it does more work than a simple assignment (check out the source code of the equals method in String for details).

Of course, most of the time readability is more important than speed, and the Guava Joiner helps you write a very clear code.

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

Comments

1

More versions

boolean addPrefix = false;
for (String serverId : serverIds) {
  if (addPrefix) {       // it's better than String.equals
      sb.append(',');    // append char is faster than append String
  } else {
      addPrefix = true;  
  }
  sb.append(serverId);
}

Assuming that serverIds is never empty this can be an allternative

for (String serverId : serverIds) {
     sb.append(serverId).append(',');
}
sb.deleteCharAt(sb.length() - 1);

If serverIds is a List then dont use for-each - it creates Iterator (Object) and Iterator.next checks for concurrent modifications

for (int i = 0; i < serverIds.size(); i++) {
  if (i > 0) {
      sb.append(',');
  }
  sb.append(serverId.get(i));
}

for arrays it is

for (int i = 0; i < serverIds.length; i++) {
  if (i > 0) {
      sb.append(',');
  }
  sb.append(serverId[i]);
}

Comments

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.