Last active
April 1, 2016 11:11
-
-
Save rocboronat/399bf617256cbe40a11a to your computer and use it in GitHub Desktop.
Comparison of 4 ways to concat Strings
This file contains 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
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); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
The result in my machine:
Adding: 257541
Concat: 178832
Buffer: 20
Builder: 14