I wrote a utility method to write some small data from a stream to a String
.
Which implementation has more performance?
- Write all data to a byte array and then convert all of them to
String
at once.
OR
- Convert each buffered part to
String
and concatenate them.
Implementation 1:
private String fileToString() throw ... {
final byte[] buffer = new byte[bufLen];
int n;
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
while ((n = fileInputStream.read(buffer)) != -1)
byteArrayOutputStream.write(buffer, 0, n);
return new String(byteArrayOutputStream.toByteArray(), "UTF-8");
}
Implementation 2:
private String fileToString() throw ... {
final byte[] buffer = new byte[bufLen];
int n;
final StringBuilder stringBuilder = new StringBuilder(aProperValue);
while ((n = fileInputStream.read(buffer)) != -1)
stringBuilder.append(new String(buffer, 0, n, "UTF-8"));
return stringBuilder.toString();
}
EDIT:
The second implementation is not correct! I was wrong! See my answer below.