Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Benchmarking String,StringBuffer and StringBuilder
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
You can’t perform that action at this time.