Sunday February 5th 2012

Insider

Archives

Optimizar las concatenaciones del texto en Java

 procesos compu 

Los problemas de perfomance al concatenar con += en vez de ocupar un objeto StringBuffer y utilizar el método append lo podemos observar en la siguiente imagen:

clip_image004

Podemos observar que si son 20 líneas, en este caso el uso del += se tarda 745.2 veces más, y entre mas líneas este número crece.

Esto se debe a que el objeto String es inmutable, por lo que cada vez que se utilizar la concatenación por medio del += se está añadiendo al Heap.

Si adicional al usar el StringBuffer, inicializamos con el numero de caracteres que tendrá la cadena (en algunos casos se pueda) podemos mejorar todavía más el perfomance de la aplicación.

Por Ejemplo -> cadenaDeTexto.setLength(300);

El código para que puedan comprobarlos por ustedes mismos es el siguiente:

public class Main {
public static void main(String[] args) {
  //Test the String Concatenation using + operator
        long startTime = System.currentTimeMillis();
        String result = "hello";
        for(int i=0;i<1500;i++){
        result += "hello3";
        result += "hello4";
        result += "hello";
        result += "hello2";
        result += "hello3";
        result += "hello4";
        result += "hello";
        result += "hello2";
        result += "hello3";
        result += "hello4";
        result += "hello3";
        result += "hello4";
        result += "hello";
        result += "hello2";
        result += "hello3";
        result += "hello4";
        result += "hello";
        result += "hello2";
        result += "hello3";
        result += "hello4";  
        
        }
        long endTime = System.currentTimeMillis();
        System.out.println("Time taken for string concatenation using += operator : "
                                        + (endTime – startTime)+ " milli seconds");
        //Test the String Concatenation using StringBuffer
        long startTime1 = System.currentTimeMillis();
        StringBuffer result1 = new StringBuffer("hello");
        result1.setLength(300);
        for(int i=0;i<1500;i++){
        result1.append("hello3");
        result1.append("hello4");
        result1.append("hello");
        result1.append("hello2");
        result1.append("hello3");
        result1.append("hello4");
        result1.append("hello");
        result1.append("hello2");
        result1.append("hello3");
        result1.append("hello4");
        result1.append("hello3");
        result1.append("hello4");
        result1.append("hello");
        result1.append("hello2");
        result1.append("hello3");
        result1.append("hello4");
        result1.append("hello");
        result1.append("hello2");
        result1.append("hello3");
        result1.append("hello4");
        
        }
        long endTime1 = System.currentTimeMillis();
        System.out.println("Time taken for string concatenation using StringBuffer.append :  " 
                                        + (endTime1 – startTime1)+ " milli seconds");
        }
/* (non-Java-doc)
* @see java.lang.Object#Object()
*/
public Main() {
super();
}
}

Reader Feedback

One Response to “Optimizar las concatenaciones del texto en Java”

  1. Oscar says:

    Thumb up 1 Thumb down 0

    Bastante interesante la prueba, tambien si se usara StringBuilder en vez de StringBuffer seria un poco mas rapido, solo que sin contar con “thread safe”

Leave a Reply


Warning: Invalid argument supplied for foreach() in /home/content/w/h/i/whibla1/html/wp-content/plugins/smilies-themer-toolbar/smilies-themer-toolbar.php on line 450