Roedy said:
The .intern is in case you are producing the same strings over and
over.
return new String( s ).intern();
To me, interning doesn't seem like the safe thing to do.
If the method is called often for the same values, then the string
itself will almost certainly be short lived. Interning just adds an
expensive operation. The additional GC is also particularly expensive,
but will be difficult to spot with a profiler.
If the method is called once and the result kept, then it doesn't really
matter where the string is.
There is a quite fun way to avoid excessive overheads when creating
varying length string of the same character repeated. Recall that
String.substring shares the underlying char array.
private String zeros = "0000";
public static String zeros(final int len) {
if (len < 0) {
throw new IllegalArgumentException()
}
for (;
{
final String zeros = ThisClass.zeros;
if (zeros.length >= len) {
return zeros.substring(0, len);
}
ThisClass.zeros = zeros+zeros;
}
}
Technically this requires Java 5.0 in order to be thread-safe.
Tom Hawtin