I have a byte[] array containing Latin-1 encoded characters, and I want to create a Java String from it.
I know I can do new String(bytes), but looking at the implementation code, it involves convoluted logic: looking up the name of the default encoding, allocating a decoder, passing the byte array to the decoder. So I suspect that (at least for short strings) the following is faster:
char[] expanded = new char[bytes.length];
for (int i=0; i<bytes.length; i++) {
expanded[i] = (char)(bytes[i] & 0xff);
}
return new String(expanded);
But that's not particularly efficient either: the String(char[]) constructor makes a copy of my newly minted char[] array, just in case I have the temerity to modify it later.
Any comments on either of these approaches? Is there a better way? (Note: most of the strings will be short. And I know I could microbenchmark this, and I know that if I did, there would be a high risk of getting wrong answers...)`