Sử dụng String#replace()
thay vì String#replaceAll()
, bạn không cần regex để thay thế một ký tự.
Tôi tạo ra lớp sau để kiểm tra những gì nhanh hơn, cung cấp cho nó một thử:
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(".", "_");
}
}
tôi nhận được kết quả như sau:
sử dụng replaceAll() hai lần: 100274
sử dụng replaceAll() một lần: 24814
sử dụng thay thế() hai lần: 31642
Tất nhiên tôi chưa lược tả ứng dụng để tiêu thụ bộ nhớ, điều đó có thể đã cho kết quả rất khác.
ah mã của tôi thậm chí không làm việc ... tôi đoán vì nó nói replaceAll sử dụng biểu thức thông thường và do đó '' là một vấn đề – ycomp