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

Validaciones con HTML5 sin necesidad de form.submit

Como parte de HTML5 existe la posibilidad de agregar información a los inputs de un form, para realizar validaciones; podemos indicar si queremos que sea requerido, con el tipo de datos; number, email, etc restringimos los valores que pueden ser agregados, podemos usar alguna mascara para validaciones, colocar mensajes de error custom, etc (en la red existen muchos ejemplos acerca de como customizar formularios). Ahora bien pongamos en contexto, tengo un formulario como este: <form name="managerForm"  id="managerForm">              <p>                  Name:                 <input id="managerNameText" required="required" placeholder="Write here the new manager name" size="40"/>              </p>             <p>                 Email:                 <input id="emailText" required="required" placeholder="myemail@myserver.com" type="email" />

Inventario anual de bebidas

Hola gente, Solo quería compartir mi inventario anual de bebidas (así conocer gustos), excluyendo algunas cervecillas que tengo por ahí guardadas, este es mi inventario: Ron: Flor de Cana 1 botella 5 anos. 2 botellas 7 anos una pacha 7 anos 2 botellas 12 anos 1 botella 18 anos Ron Zacapa 15 anos Centenario pachita 7 anos Centanario pachita 12 anos Bacardi limon Bacardi Razz Ron abuelo 7 anos Bacardi superior 1862 Ron Boltran XL Ron Centenario Garrafon Ron Jamaica Appleton 7 anos Ron Jamaica Appleton 12 anos (muchisimas gracias a Mayra :) Capitan Morgan Rum Jumbie, coconnut splash Ron coconut Malibu Ron Tequila Milagro Silver (muchisimas gracias a Pablito :) Sauza Gold Sauza Reposado Don Julio Reposado Vino Luigi Borer Malbec 2006 Casillero del Diablo, Caberut Sauviguon 2009 Vodka 2 botellas smirnoff y una smirnoff con sabor cranberry Cremas y otro licores Cahuita pacha Amaretto Barinet Licor de menta Licor de agave Rancho Escondido Bayleys 2 botellas (muchisimas gracias a Brian B :) Li