Per la concatenazione di stringhe, è possibile utilizzare l'operatore concat()
o concatenato (+)
.Operatore di concatenazione (+) vs. concat()
Ho provato il seguente test delle prestazioni e ho trovato concat()
più veloce e un modo efficiente per la memorizzazione della stringa.
stringa di confronto concatenazione per 100.000 volte:
String str = null;
//------------Using Concatenation operator-------------
long time1 = System.currentTimeMillis();
long freeMemory1 = Runtime.getRuntime().freeMemory();
for(int i=0; i<100000; i++){
str = "Hi";
str = str+" Bye";
}
long time2 = System.currentTimeMillis();
long freeMemory2 = Runtime.getRuntime().freeMemory();
long timetaken1 = time2-time1;
long memoryTaken1 = freeMemory1 - freeMemory2;
System.out.println("Concat operator :" + "Time taken =" + timetaken1 +
" Memory Consumed =" + memoryTaken1);
//------------Using Concat method-------------
long time3 = System.currentTimeMillis();
long freeMemory3 = Runtime.getRuntime().freeMemory();
for(int j=0; j<100000; j++){
str = "Hi";
str = str.concat(" Bye");
}
long time4 = System.currentTimeMillis();
long freeMemory4 = Runtime.getRuntime().freeMemory();
long timetaken2 = time4-time3;
long memoryTaken2 = freeMemory3 - freeMemory4;
System.out.println("Concat method :" + "Time taken =" + timetaken2 +
" Memory Consumed =" + memoryTaken2);
Risultato
Concat operator: Time taken = 31; Memory Consumed = 2259096
Concat method : Time taken = 16; Memory Consumed = 299592
Se concat()
è più veloce l'operatore poi quando dovremmo usare operatore di concatenamento (+)
?
Leggi: http://stackoverflow.com/questions/693597/is-there-a-difference-between-string-concat-and-the-operator-in-java e http://stackoverflow.com/questions/47605/java-string-concatenation –
L'unica cosa che sembra diversa è quando la stringa che si sta aggiungendo ha una lunghezza pari a zero, ma restituisce l'originale invece di creare una nuova stringa. L'operatore + può essere un po 'costoso ... se stai facendo centinaia o migliaia di operazioni di costruzione di stringhe, cerca in StringBuffer.append(). È normale vedere un metodo creare un oggetto StringBuffer e quindi restituire o utilizzare ilBuffer.toString() alla fine. –
@PankajKumar bene, probabilmente vuoi StringBuilder invece di StringBuffer – ymajoros