Last active
October 2, 2015 21:30
-
-
Save ripper2hl/867df343cae0a72895ff to your computer and use it in GitHub Desktop.
Benchmarking String,StringBuffer and StringBuilder
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
public class Application { | |
long start; | |
long end; | |
final long numberIterations = 100000000; | |
public static void main(String[] args){ | |
Application app = new Application(); | |
System.out.println(app.testStringBuffer()); | |
System.out.println(app.testStringBuilder()); | |
System.out.println(app.testStringWithConcat()); | |
System.out.println(app.testStringWithoutConcat()); | |
} | |
/** | |
* Metodo que concatena palabras zim en | |
* un objeto del tipo String utilizando | |
* el metodo concat | |
* @return Descripcion del tiempo que se tardo en concatenar. | |
*/ | |
public String testStringWithConcat(){ | |
//String | |
String string = new String(); | |
start = System.currentTimeMillis(); | |
for (int i=0; i<numberIterations; i++) { | |
string = string.concat("zim"); | |
} | |
end = System.currentTimeMillis(); | |
return "Tiempo del String: " + (end-start); | |
} | |
/** | |
* Metodo que concatena palabras zim en | |
* un objeto del tipo String utilizando | |
* el operador + | |
* @return Descripcion del tiempo que se tardo en concatenar. | |
*/ | |
public String testStringWithoutConcat(){ | |
//String | |
String string = new String(); | |
start = System.currentTimeMillis(); | |
for (int i=0; i<numberIterations; i++) { | |
string += "zim"; | |
} | |
end = System.currentTimeMillis(); | |
return "Tiempo del String: " + (end-start); | |
} | |
/** | |
* Metodo que concatena palabras zim en | |
* un objeto del tipo StringBuffer | |
* @return Descripcion del tiempo que se tardo en concatenar. | |
*/ | |
public String testStringBuffer(){ | |
//StringBuffer | |
StringBuffer sbuffer = new StringBuffer(); | |
start = System.currentTimeMillis(); | |
for (int i=0; i<numberIterations; i++) { | |
sbuffer.append("zim"); | |
} | |
end = System.currentTimeMillis(); | |
return "Tiempo del StringBuffer: " + (end-start); | |
} | |
/** | |
* Metodo que concatena palabras zim en | |
* un objeto del tipo StringBuilder | |
* @return Descripcion del tiempo que se tardo en concatenar. | |
*/ | |
public String testStringBuilder(){ | |
//StringBuilder | |
StringBuilder sbuilder = new StringBuilder(); | |
start = System.currentTimeMillis(); | |
for (int i=0; i<numberIterations; i++) { | |
sbuilder.append("zim"); | |
} | |
end = System.currentTimeMillis(); | |
return "Tiempo del StringBuilder: " + (end-start); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://www.ingenieroperales.com/2015/09/30/diferencias-entre-string-stringbuffer-y-stringbuilder-java/