Ir al contenido principal

Test de eficiencia en concatenación de Java String.

El siguiente código resulta muy interesante, en el grado que nos permite experimentar con diferentes implementaciones de CharSequence, para concatenar caracteres (string con +, string utilizando el método concat, StringBuilder, StringBuffer y una biblioteca de terceros que implementa un nuevo objeto llamado Ropes, el cual asegura ser mas rápido y eficiente que el StringBuffer y el simple String (+ info: http://ahmadsoft.org/ropes/).

Los resultados a la vista son muy interesantes, el StringBuilder gana la lucha en eficiencia y eficacia. Y la razón del resultado recae en la estrategia de bufereo y que el objeto no sea sincronizado, muy cerca le sigue el StringBuffer el cual utiliza la misma estrategia de buffering, sin embargo es un objeto sincronizado, seguido por la biblioteca propietaria Ropes, la utilizaron del método String.concat() se encuentra de penúltima, la ultima y altamente no recomendable es la utilización del operador + para concatenar; esta operación no solo es lenta, también utiliza mucha memoria y hace que nuestra aplicación ocupe mas tiempo de proceso, practicamente mas de 250 veces mas lento en el manejo intensivo de concatenación que utilizar StringBuilder.

Aquí los resultados:

47 = StringBuilder
52 = StringBuffer
286 = Ropes
61079 = String.concat().
137514 = string = string1 + string2;
Este resultado se encuentra en milli segundos.



import java.util.Map;
import java.util.TreeMap;

import org.ahmadsoft.ropes.Rope;


public class ConcatenationStringExample {

public void concat() {

Map resultTimeMap = new TreeMap ();
Map resultMenMap = new TreeMap ();
final CharSequence s = "Hello classmate, this is the concatening example, !@#$%^&*()_+, @@@###@@@ 1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111======================blauppee";
final int repeat = 6000;


long totalTime = 0;
long totalMem = 0;

long iniMem = Runtime.getRuntime().freeMemory();
long initTime = System.currentTimeMillis();

this.simpleConcatString(s, repeat);

totalTime = System.currentTimeMillis() - initTime;
totalMem = iniMem - Runtime.getRuntime().freeMemory();

System.out.println("Total time in millis: " + totalTime
+ ", total memory used: " + totalMem);

resultTimeMap.put(totalTime, "simpleConcatString");
resultMenMap.put(totalMem, "simpleConcatString");
System.gc();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
/**/
}
// //////////////////////////////////////////////////////////////
iniMem = Runtime.getRuntime().freeMemory();
initTime = System.currentTimeMillis();

this.concatString(s, repeat);

totalTime = System.currentTimeMillis() - initTime;
totalMem = iniMem - Runtime.getRuntime().freeMemory();

System.out.println("Total time in millis: " + totalTime
+ ", total memory used: " + totalMem);

resultTimeMap.put(totalTime, "concatString");
resultMenMap.put(totalMem, "concatString");
System.gc();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
/**/
}
// //////////////////////////////////////////////////////////////
iniMem = Runtime.getRuntime().freeMemory();
initTime = System.currentTimeMillis();

this.concatStringBuffer(s, repeat);

totalTime = System.currentTimeMillis() - initTime;
totalMem = iniMem - Runtime.getRuntime().freeMemory();

System.out.println("Total time in millis: " + totalTime
+ ", total memory used: " + totalMem);

resultTimeMap.put(totalTime, "concatStringBuffer");
resultMenMap.put(totalMem, "concatStringBuffer");
System.gc();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
/**/
}
// //////////////////////////////////////////////////////////////
iniMem = Runtime.getRuntime().freeMemory();
initTime = System.currentTimeMillis();

this.concatStringBuilder(s, repeat);

totalTime = System.currentTimeMillis() - initTime;
totalMem = iniMem - Runtime.getRuntime().freeMemory();

System.out.println("Total time in millis: " + totalTime
+ ", total memory used: " + totalMem);

resultTimeMap.put(totalTime, "concatStringBuilder");
resultMenMap.put(totalMem, "concatStringBuilder");
System.gc();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
/**/
}
// //////////////////////////////////////////////////////////////
iniMem = Runtime.getRuntime().freeMemory();
initTime = System.currentTimeMillis();

this.concatRopes(s, repeat);

totalTime = System.currentTimeMillis() - initTime;
totalMem = iniMem - Runtime.getRuntime().freeMemory();

System.out.println("Total time in millis: " + totalTime
+ ", total memory used: " + totalMem);

resultTimeMap.put(totalTime, "concatRopes");
resultMenMap.put(totalMem, "concatRopes");

System.out.println("***************-*******************");
System.out.println("time results with " + (repeat) + " repeat :" + resultTimeMap.toString().replaceAll(",","\n"));
System.out.println("Memory results with " + (repeat) + " repeat :" + resultMenMap.toString().replaceAll(",","\n"));

} // concat.

private void concatRopes(final CharSequence sequence, final int repeat) {

Rope string = null;

string = Rope.BUILDER.build(sequence);
for (int i = 0; i < Math.abs(repeat); ++i) {

string = string.append(sequence.toString());
}
System.out.println("concatRopes length: " + string.length());
} // concatRopes.


private void concatStringBuilder(final CharSequence sequence, final int repeat) {

StringBuilder string = null;

string = new StringBuilder(sequence);
for (int i = 0; i < Math.abs(repeat); ++i) {

string.append(sequence);
}
System.out.println("concatStringBuilder length: " + string.length());
} // concatStringBuilder.


private void concatStringBuffer(final CharSequence sequence, final int repeat) {

StringBuffer string = null;

string = new StringBuffer(sequence);
for (int i = 0; i < Math.abs(repeat); ++i) {

string.append(sequence);
}
System.out.println("concatStringBuffer length: " + string.length());
} // concatStringBuffer.


private void concatString(final CharSequence sequence, final int repeat) {

String string = null;

string = new String(sequence.toString());
for (int i = 0; i < Math.abs(repeat); ++i) {

string = string.concat(sequence.toString());
}

System.out.println("concatString length: " + string.length());
} // concatString.

private void simpleConcatString(final CharSequence sequence,
final int repeat) {

String string = null;

string = new String(sequence.toString());
for (int i = 0; i < Math.abs(repeat); ++i) {

string = string + sequence;
}

System.out.println("simpleConcatString length: " + string.length());
} // concatString.

public static void main(String[] args) {

ConcatenationStringExample example = new ConcatenationStringExample();
example.concat();
}
} // ConcatenationStringExample.

Comentarios

Entradas más populares de este blog

Impensando acerca de las referencias en Java

Fue hace ya algún tiempo que pase un rato discutiendo con algunos compañeros acerca de si existe o no el paso por referencia; el discurso fue mucho hacia que en Java el comportamiento, en el supuestamente pasamos por referencia un objeto y por valor los objetos primitivos creo mucha polémica. Para ubicarnos en contexto veamos el siguiente ejemplo. public static void main(String[] args) { int value = 10; changeValue(value); System.out.println("value = " + value); User user = new User(); Name name = new Name(); user.setName(name); name.setName("jsanca"); name.setLastName("XXX"); user.setPassword("123queso"); System.out.println("user: " + user.getName().getName() + ", " + user.getName().getLastName() + ", " + user.getPassword()); changeValue1(user); System.out.println("user: " + user.getName().getName() + ", " + user.getName().getLastName() + ", " + user.ge...

Analizador de expresiones algebraicas recursivo decendente

Como les mencione en un post previo, estoy leyendo el libro el arte de programar en Java, el primer ejercicio consiste en un analizador de expresiones algebraicas recursivo descendente, el mismo consiste en la posibilidad de tomar una cadena que contenga una expresión matemática, la misma puede contener valores en punto flotante, sumar, restar, dividir, multiplicar, sacar exponente (potencia), uso de paréntesis para priorizar una operación, etc. A continuación clase a clase, con una pequeña explicación Lo primero que definiremos es una suite de excepciones para reportar errores, no tiene mucha ciencia, hay una para la division entre cero, cuando no existe una expresión valida, error de sintaxis o cuando los paréntesis no se encuentran balanceados, veamos package cap2; /** * Exception para reportar que hay al intentar dividir entre cero * * User: jsanca * Date: 4/16/13 * Time: 1:30 AM * @author jsanca */ public class DividedByZeroException extends RuntimeException { ...

Links acerca de usabilidad

Bueno esta haciendo un research acerca de usabilidad y decidi compartir algunos de los links mas interesantes: Este esta muy cool y dice por que son buenos, gmail #1: http://www.1stwebdesigner.com/design/well-designed-usable-sites/ Los mejores menus: http://www.kronikmedia.co.uk/blog/website-navigation-menu-design/3580/ Otro top ten: http://www.topsite.com/best/usability los CMS con mas usabilidad http://net.tutsplus.com/articles/web-roundups/top-10-most-usable-content-management-systems/ Las grandes companias que incorporan usabilidad en sus sistemas: http://www.siteiq.net/7806/the-2013-usability-top-10-ibm-leads-sap-soars-and-apple-screws-up-the-rankings-2 + Algo interesante: top ten de sitios de Universidades http://blog.thebrickfactory.com/2010/03/top-11-best-designed-university-websites/ Y estos son 10 videitos acerca de usabilidad: http://www.usefulusability.com/10-must-see-usability-videos/ Enjoy!