Skip to content

Instantly share code, notes, and snippets.

@sangupta
Created October 5, 2020 23:50
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 sangupta/49baa6f1feaac9c85043c4949190c5ae to your computer and use it in GitHub Desktop.
Save sangupta/49baa6f1feaac9c85043c4949190c5ae to your computer and use it in GitHub Desktop.
A simple benchmark to compare performance of String.join() and String concatenation for 2 arguments.
public class StringJoinBenchmark {
public static void main(String[] args) {
final int MAX_ITER = 1000 * 1000;
final int RUNS = 1;
long delta = 0;
long delta2 = 0;
for(int run = 0; run < RUNS; run++) {
long start = System.nanoTime();
for(int index = 0; index < MAX_ITER; index++) {
String merged1 = String.join("-", "prefix", "suffix");
}
long end = System.nanoTime();
long start2 = System.nanoTime();
for(int index = 0; index < MAX_ITER; index++) {
String merged2 = "prefix" + "-" + "suffix";
}
long end2 = System.nanoTime();
delta += (end - start);
delta2 += (end2 - start2);
}
double ratio = (double) delta / (double) delta2;
System.out.println("Ratio: " + ratio);
}
}
@sangupta
Copy link
Author

sangupta commented Oct 5, 2020

Multiple single runs provide speed improvement ratio's as:

Ratio: 102.10164665754219
Ratio: 96.11536413565226
Ratio: 101.20484979369964
Ratio: 103.62282307180902
Ratio: 102.89166083318867

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