// is this better? sb.append( source.substring(nStart, nEnd) );
// or is this? sb.append( source, nStart, nEnd );
My initial thought was that the one that doesn't call String.substring() would be better (since a new String object doesn't have to be created) but looking at the code that one seems to copy the chars one by one in a loop, while the String.substring() one eventually uses System.arraycopy().
The easiest way to tell would just time it. Run both methods (try with a large string) and see if there is any difference.
Joined: Sep 20, 2005
Originally posted by Jeff Storey: The easiest way to tell would just time it. Run both methods (try with a large string) and see if there is any difference.
Heh. I had trouble deciding whether to post in the Intermediate forum or the Advanced one. I chose Advanced and it gets bumped to Beginner.
Anyway, for my app it doesn't really matter. Even though I'm doing it in a loop, it's not really on a critical path. So I probably won't go to the trouble of timing it. I just thought it was an interesting API issue.
One would think the single call to append(CharSequence s, int start, int end) would be the way to go, I think, but looking at the JDK 1.5 implementation it seems not. It doesn't seem to be optimized for the case when the Char- Sequence happens to be a String, even though append(CharSequence s) is.
On the otherhand, String.subString() is surprisingly time-efficient (some- times at the expense of keeping a large array un-garbage-collectable).
Understood. What I meant was I'm interested in the efficiency trade-offs between sb.append(source.substring(nStart, nEnd)) and sb.append(source, nStart, nEnd) on StringBuilder and also on StringBuffer. I wouldn't say it's likely, but it could be that one is better on StringBuilder and the other is better on StringBuffer.