Skip to content

Instantly share code, notes, and snippets.

@rstiller
Created July 31, 2012 11:47
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/3216398 to your computer and use it in GitHub Desktop.
Save rstiller/3216398 to your computer and use it in GitHub Desktop.
StringPerformanceTest (String to bytes)
package test;
import java.nio.charset.Charset;
import org.junit.Test;
public class StringPerformanceTest {
@Test
public void stringToBytes() throws Exception {
for (int i = 0; i < 10; i++) {
stringToBytes(10000000);
}
}
public void stringToBytes(final int count) throws Exception {
long start, end;
String data = "MyData";
Charset utf8 = Charset.forName("utf-8");
byte[] tmp = new byte[16];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 10; j++) {
data.getBytes();
}
Thread.sleep(100);
}
start = System.currentTimeMillis();
for (int j = 0; j < count; j++) {
data.getBytes();
}
end = System.currentTimeMillis();
System.out.format("(unicode) 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++) {
data.getBytes(utf8);
}
Thread.sleep(100);
}
start = System.currentTimeMillis();
for (int j = 0; j < count; j++) {
data.getBytes(utf8);
}
end = System.currentTimeMillis();
System.out.format("(utf-8) 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++) {
stringToBytesLoop(data, tmp);
}
Thread.sleep(100);
}
start = System.currentTimeMillis();
for (int j = 0; j < count; j++) {
stringToBytesLoop(data, tmp);
}
end = System.currentTimeMillis();
System.out.format("(loop) duration: %d ms, ratio: %.4f", end - start, count / ((end - start) / 1000.0));
System.out.println();
}
void stringToBytesLoop(final String source, final byte[] dest) {
for (int i = 0; i < source.length(); i++) {
dest[i] = (byte) source.charAt(i);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment