OK, here was my version:
I figure it toCharArray() was allowec, why not getChars()? That way there's no time wasted copying chars to the wrong position.
Still, performance-wise we can't really beat
or the equivalent
The main advantage these have over any solution that builds a char[] array is that they can take advantage of the new String(StringBuffer) constructor, which is optimized so that it can build a String using the
same internal char[] array which the StringBuffer was using. Which is very fast; no new char[] is created, and no copying needs to be done. In comparison, the new String(char[]) constructor is slower because it must make a copy of the char[] for internal use by the String. The reason for this is that String must be immutable; it can't just take a char[] from yyou and assume it will never change. It has to make its own private copy to ensure that it doesn't change.
So, why can a StringBuffer be trusted while a char[] cannot? Because StringBuffer is written so as to pay attention to whether any Strings are sharing its internal char[]. If there are, then if the StringBuffer is subsequently modified it protects the shared char[] by first copying it and then modifying the copy. This means that the previously-shared char[] can now be left to be owned solely by the immatable String class that is using it. So basically, StringBuffer is trusted because the StringBuffer authors have made sure it will never change a char[] that is shared with a String.