Skip to content

Instantly share code, notes, and snippets.

@rocboronat
Last active April 1, 2016 11:11
Show Gist options
  • Save rocboronat/399bf617256cbe40a11a to your computer and use it in GitHub Desktop.
Save rocboronat/399bf617256cbe40a11a to your computer and use it in GitHub Desktop.
Comparison of 4 ways to concat Strings
package com.fewlaps;
public class ConcatStringComparison {
static long timeAdding;
static long timeConcat;
static long timeStringBuffer;
static long timeStringBuilder;
public static final int ITERATIONS = 1000000;
public static void main(String[] args) {
long now = System.currentTimeMillis();
String something = "";
for (int i = 0; i < ITERATIONS; i++) {
something = something + "a";
}
timeAdding = System.currentTimeMillis() - now;
now = System.currentTimeMillis();
something = "";
for (int i = 0; i < ITERATIONS; i++) {
something = something.concat("a");
}
timeConcat = System.currentTimeMillis() - now;
now = System.currentTimeMillis();
StringBuffer sbuffer = new StringBuffer();
for (int i = 0; i < ITERATIONS; i++) {
sbuffer.append("a");
}
timeStringBuffer = System.currentTimeMillis() - now;
now = System.currentTimeMillis();
StringBuilder sbuilder = new StringBuilder();
for (int i = 0; i < ITERATIONS; i++) {
sbuilder.append("a");
}
timeStringBuilder = System.currentTimeMillis() - now;
System.out.println("Adding: " + timeAdding);
System.out.println("Concat: " + timeConcat);
System.out.println("Buffer: " + timeStringBuffer);
System.out.println("Builder: " + timeStringBuilder);
}
}
@rocboronat
Copy link
Author

The result in my machine:

Adding: 257541
Concat: 178832
Buffer: 20
Builder: 14

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment