字符串匹配的效率,Equals 与 Matches 方法
Efficiency of String matching, Equals vs. Matches methods
假设我必须比较 Java 中的一些字符串对象,并且对于一个大容量程序我必须这样做一百万次。这些字符串要么完全相同,要么不应算作匹配。哪种方法使用起来更有效,等于(对象相等)或匹配(正则表达式)?一个例子:
String a = "JACK", b = "JACK", c = "MEG";
a.equals(b);//True
a.equals(c);//False
a.matches(b);//True
a.matches(c);//False
这两种方法都能得到我想要的结果,但我想知道考虑到大量处理,哪种方法效率更高。
您可以通过获取大量字符串并在循环中比较它们来自行检查。循环前后,取当前系统时间,然后得到开始时间和结束时间的差值。请参阅此处:Runtime。但是您应该小心,因为结果可能因您的硬件而异。了解 JVM 可能在后台进行的优化也很重要。这就是为什么你应该比较许多字符串并可能取平均值的原因
List<String> bigList = new List<String>(); // put many many values in this list
String pattern = "pattern";
long start = System.nanoTime();
for(int i=0;i<bigList.length;i++) {
bigList.get(i).equals(pattern); //in another program, check for matches(pattern)
}
long end = System.nanoTime();
System.out.println((end-start)/bigList.size()) // this is the average time
matches will probably be slower since it uses a java.util.regex.Pattern and java.util.regex.Matcher in the background. Both equals and compareTo use a simple loop, and should therefore be faster.
在此处找到答案:http://www.coderanch.com/t/487350/Performance/java/compare-strings
假设我必须比较 Java 中的一些字符串对象,并且对于一个大容量程序我必须这样做一百万次。这些字符串要么完全相同,要么不应算作匹配。哪种方法使用起来更有效,等于(对象相等)或匹配(正则表达式)?一个例子:
String a = "JACK", b = "JACK", c = "MEG";
a.equals(b);//True
a.equals(c);//False
a.matches(b);//True
a.matches(c);//False
这两种方法都能得到我想要的结果,但我想知道考虑到大量处理,哪种方法效率更高。
您可以通过获取大量字符串并在循环中比较它们来自行检查。循环前后,取当前系统时间,然后得到开始时间和结束时间的差值。请参阅此处:Runtime。但是您应该小心,因为结果可能因您的硬件而异。了解 JVM 可能在后台进行的优化也很重要。这就是为什么你应该比较许多字符串并可能取平均值的原因
List<String> bigList = new List<String>(); // put many many values in this list
String pattern = "pattern";
long start = System.nanoTime();
for(int i=0;i<bigList.length;i++) {
bigList.get(i).equals(pattern); //in another program, check for matches(pattern)
}
long end = System.nanoTime();
System.out.println((end-start)/bigList.size()) // this is the average time
matches will probably be slower since it uses a java.util.regex.Pattern and java.util.regex.Matcher in the background. Both equals and compareTo use a simple loop, and should therefore be faster.
在此处找到答案:http://www.coderanch.com/t/487350/Performance/java/compare-strings