Created
October 5, 2020 23:50
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Multiple single runs provide speed improvement ratio's as: