Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Benchmark string concatenation (version 1)
import java.util.HashMap;
import org.apache.commons.lang3.RandomStringUtils;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
public class StringConcat extends SimpleBenchmark {
private final static int CONCATENATIONS = 5;
private HashMap<Integer, String> strings = new HashMap<Integer, String>();
@Override
protected void setUp() throws Exception {
super.setUp();
strings.clear();
for (int i = 0; i < CONCATENATIONS; i++) {
String s = RandomStringUtils.randomAlphabetic(10);
strings.put(i, s);
}
}
/**
* Use '+' to concat strings
* @param reps
*/
public void timeStringAddition(int reps) {
for (int n = 0; n < reps; n++) {
String concat = strings.get(0) + strings.get(1) + strings.get(2) + strings.get(3) + strings.get(4);
}
}
/**
* Use {@link StringBuilder} to concat strings
* @param reps
*/
public void timeStringBuilder(int reps) {
for (int n = 0; n < reps; n++) {
StringBuilder sb = new StringBuilder();
String concat = sb.append(strings.get(0)).append(strings.get(1)).append(strings.get(2)).append(strings.get(3)).append(strings.get(4)).toString();
}
}
/**
* Use {@link StringBuffer} to concat strings
* @param reps
*/
public void timeStringBuffer(int reps) {
for (int n = 0; n < reps; n++) {
StringBuffer sb = new StringBuffer();
String concat = sb.append(strings.get(0)).append(strings.get(1)).append(strings.get(2)).append(strings.get(3)).append(strings.get(4)).toString();
}
}
public static void main(String... args) throws Exception {
Runner.main(StringConcat.class, args);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment