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

Pasos para remover Postgresql 8.3 en MAC OS

Tomado de: http://forums.enterprisedb.com/posts/list/1437.page In Mac OSX: (Assuming Default Locations) Via uninstaller: 1) In the installation directory, there will be a uninstall-postgresql.app file will be there, executing (double clicking) that will uninstall the postgresql installation. Manual Uninstallation: 1) Stop the server sudo /sbin/SystemStarter stop postgresql-8.3 2) Remove menu shortcuts: sudo rm -rf /Applications/PostgreSQL 8.3 3) Remove the ini file sudo rm -rf /etc/postgres-reg.ini 4) Removing Startup Items sudo rm -rf /Library/StartupItems/postgresql-8.3 5) Remove the data and installed files sudo rm -rf /Library/PostgreSQL/8.3 6) Delete the user postgres sudo dscl . delete /users/postgres

Enrique Bunbury - 3 de Octubre 2009 - Heredia CR

Via periodico la nacion, me entero de este conciertazo: http://www.nacion.com/viva/2009/julio/29/viva2042768.html Ah esperar mas detalles y la venta de la entradas, "Para solo si me perdonas ..." EDIT ..... Via http://www.enriquebunbury.com/hellville.aspx (gracias a andres por su post) venta anticipada: Entradas a la venta a partir del 13 de agosto en: www.costaricaticket.com Por ahi estare anunciando, el 13 si las estan vendiendo!

Configura tu MMS - ICE CELULAR

Hola gente, Me encontre esta para configurar en tu aparato el servicio del ICE, para enviar mensajes con Imagen: http://www.grupoice.com/esp/serv/per/cel/catal_sm/men_multi/guia.htm En mi caso yo tengo un K550i, aunque no vi mi modelo dentro de la lista que dan en el PDF, me guié con el modelo mas similar y funko. Como dato curioso si envía un mensaje a un celular sin soporte o conflagración MMS, el ICE manda un link y credenciales para ver el mensaje en: http://mms.grupoice.com/m/C?url=mmc1 upd (edit): Para que funcione los MMS debe tener instalado Internet en su Celular; el costo por tarifa fija, es de 3500 colones por mes. update (dic 29 2010) Me encontré estos otros links con mas info: http://portal.grupoice.com/wps/wcm/connect/web+content/Esp/CatTelecom/movil/Adicionales/Kolbiemail/como/ http://www.taringa.net/posts/celulares/7987334/Kolbi-Prepago-todas-la-configuraciones.html También puedes ver mas, en el thread del facebook de Kolbi http://www.facebook.com/photo.php?fbid=1720708...