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);
}
Community
  • 1
  • 1
ubiquibacon
  • 9,834
  • 25
  • 101
  • 175

2 Answers2

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.

lbalazscs
  • 16,476
  • 7
  • 39
  • 48
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]);
}
Evgeniy Dorofeev
  • 124,221
  • 27
  • 187
  • 258