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 { ...

Canvas - Dibujando poligonos con Javascript (Herencia y pseudo polimorfismo)

En el ejemplo anterior definimos de una manera muy basica varios poligonos, bueno decidi buscar la manera de pintarlos en un lienzo (canvas) y aqui el resultado (ojo necesitas un browser que soporte HTML 5) Lo primero el HTML <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"         "http://www.w3.org/TR/html4/loose.dtd"> <html> <head>     <title>Figure Example</title> </head> <body>     <canvas id="myCanvas" width="300" height="300" style="border: solid 1px black"></canvas>     <script type="text/javascript" src="figure.js"></script> </body> </html> Note q al javascript le hemos dado el nombre de figure.js Seguidamente el codigo con el canvas, es bastante sencillo para mas detalles busque la documentacion de cada metodo. /** * User: jsanca * Date: 6/12/13 * Time: 11:10 PM */ // Define...