As already said, the String
approach is pretty bad. Using StringBuffer
is much better, but there's no reason for this rather obsolete class, when StringBuilder
can do the same faster.
Even simpler and faster in this case is to use an array:
char[] result = new char[source.length];
for(int i = 0; i < source.length(); ++i) result[source.length() - 1 - i] = source.charAt(i);
return new String(result);
This allocates no garbage at all.... except for the char[]
, but this is unavoidable as String is immutable and the sharing constructor is package-private (for a good reason).
Note that usually there's absolutely no need to optimize that hard.