Utilizzare String#replace()
anziché String#replaceAll()
, non è necessario regex per la sostituzione di un solo carattere.
ho creato la seguente classe di verificare ciò che è più veloce, fare un tentativo:
public class NewClass {
static String s = "some_string with spaces _and underlines";
static int nbrTimes = 10000000;
public static void main(String... args) {
long start = new Date().getTime();
for (int i = 0; i < nbrTimes; i++)
doOne();
System.out.println("using replaceAll() twice: " + (new Date().getTime() - start));
long start2 = new Date().getTime();
for (int i = 0; i < nbrTimes; i++)
doTwo();
System.out.println("using replaceAll() once: " + (new Date().getTime() - start2));
long start3 = new Date().getTime();
for (int i = 0; i < nbrTimes; i++)
doThree();
System.out.println("using replace() twice: " + (new Date().getTime() - start3));
}
static void doOne() {
String new_s = s.toLowerCase().replaceAll(" ", "_").replaceAll(".", "_");
}
static void doTwo() {
String new_s2 = s.toLowerCase().replaceAll("[ .]", "_");
}
static void doThree() {
String new_s3 = s.toLowerCase().replace(" ", "_").replace(".", "_");
}
}
ottengo il seguente output:
utilizzando replaceAll() due volte: 100274
utilizzando replaceAll() una volta: 24814
utilizzando replace() due volte: 31642
Ovviamente non ho profilato l'app per il consumo di memoria, che avrebbe potuto dare risultati molto diversi.
ah il mio codice non ha nemmeno funziona ... credo perché dice replaceAll utilizza espressioni regolari e così il '' è un problema – ycomp