Используйте String#replace()
вместо String#replaceAll()
, вам не нужно регулярное выражение для замены одного символа.
Я создал следующий класс, чтобы проверить, что быстрее, попробуйте:
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(".", "_");
}
}
Я получаю следующий вывод:
с использованием replaceAll () дважды: 100274
с использованием replaceAll () один раз: 24814
с использованием replace () дважды: 31642
Конечно, я не профилировал приложение для потребления памяти, которое могло бы дать совсем другие результаты.