Using a list for this purpose is not ergonomic,
which is very noticeable in the toString
implementations of your two approaches (the second one is spot-on).
For a reasonably fast solution,
a char[]
is clearly the way to go.
No need to name it characterBuffer
,
you don't normally put the type's name in the name.
So buffer
is nice and simple for this purpose.
A StringBuilder
implementation will probably not need any other kind of buffer anyway.
As @maaartinus pointed out, the biggest problem in both of your implementations is the throw-away char[]
allocations. Be careful with that,
it's a big mistake.
Perhaps the approach they were looking for is the technique taken by the JDK's StringBuilder implementation:
using String.getChars
to copy characters from a source string to a target char[]
at some offset and with some length, like this:
if (str == null) str = "null";
int len = str.length();
ensureCapacityInternal(count + len);
str.getChars(0, len, value, count);
count += len;
return this;
Now that looks unbeatable in terms of performance.
- 113k
- 15
- 154
- 396