Just to amplify the previous comments:
From looking at source, delete
() always calls System.arraycopy
(), but if the arguments are (0,count), it will call arraycopy
() with a length of zero, which will presumably have no effect. IMHO, this should be optimized out since I bet it's the most common case, but no matter.
With setLength
(), on the other hand, the call will increase the StringBuilder's capacity if necessary via a call to ensureCapacityInternal
() (another very common case that should have been optimized out IMHO) and then truncates the length as delete
() would have done.
Ultimately, both methods just wind up setting count
to zero.
Neither call does any iterating in this case. Both make an unnecessary function call. However ensureCapacityInternal() is a very simple private method, which invites the compiler to optimize it nearly out of existence so it's likely that setLength
() is slightly more efficient.
I'm extremely skeptical that creating a new instance of StringBuilder could ever be as efficient as simply setting count
to zero, but I suppose that the compiler might recognize the pattern involved and convert the repeated instantiations into repeated calls to setLength
(0). But at the very best, it would be a wash. And you're depending on the compiler to recognize the case.
Executive summary: setLength(0) is the most efficient. For maximum efficiency, pre-allocate the buffer space in StringBuilder when you create it.