Skip to content

Instantly share code, notes, and snippets.

@rstiller
Created July 31, 2012 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rstiller/3217422 to your computer and use it in GitHub Desktop.
Save rstiller/3217422 to your computer and use it in GitHub Desktop.
ByteToStringPerformanceTest
package test;
import org.junit.Test;
public class StringPerformanceTest {
@Test
public void bytesToString() throws Exception {
for (int i = 0; i < 10; i++) {
bytesToString(10000000);
}
}
public void bytesToString(final int count) throws Exception {
long start, end;
byte data[] = "MyData".getBytes();
StringBuilder builder = new StringBuilder(16);
char[] buffer = new char[16];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
new String(data);
}
Thread.sleep(100);
}
start = System.currentTimeMillis();
for (int j = 0; j < count; j++) {
new String(data);
}
end = System.currentTimeMillis();
System.out.format("(new) duration: %d ms, ratio: %.4f", end - start, count / ((end - start) / 1000.0));
System.out.println();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
stringBuilder(data, builder);
}
Thread.sleep(100);
}
start = System.currentTimeMillis();
for (int j = 0; j < count; j++) {
stringBuilder(data, builder);
}
end = System.currentTimeMillis();
System.out.format("(builder) duration: %d ms, ratio: %.4f", end - start, count / ((end - start) / 1000.0));
System.out.println();
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
stringValueOf(data, buffer);
}
Thread.sleep(100);
}
start = System.currentTimeMillis();
for (int j = 0; j < count; j++) {
stringValueOf(data, buffer);
}
end = System.currentTimeMillis();
System.out.format("(valueOf) duration: %d ms, ratio: %.4f", end - start, count / ((end - start) / 1000.0));
System.out.println();
}
String stringBuilder(final byte[] data, final StringBuilder builder) {
builder.delete(0, builder.length());
for (int i = 0; i < data.length; i++) {
builder.append((char) data[i]);
}
return builder.toString();
}
String stringValueOf(final byte[] data, final char[] buffer) {
for (int i = 0; i < data.length; i++) {
buffer[i] = (char) data[i];
}
return String.valueOf(buffer, 0, data.length);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment