Tag Archives: cpu opti

Inefficient byte[] to String constructor

by Mikhail Vorontsov

Everything written in this post is related to Java 6 only.

A String constructor was added in Java 6 in order to facilitate conversion from byte[] to String using a provided Charset:

1
public String(byte bytes[], int offset, int length, Charset charset)
public String(byte bytes[], int offset, int length, Charset charset)

It looks harmless from the first sight, but it has a potential problem inside: it makes a temporary “defensive” copy of a provided byte[] inside StringCoding.decode(Charset cs, byte[] ba, int off, int len) method. It may be needed in a very few applications, but most applications will pay unfair price for this method call.

Continue reading