比较字符串时,其中一种方法是否有任何优势?
答案 0 :(得分:1)
未使用数据集进行测试,但检查compareTo和matches的源代码
似乎compareTo
会更快matches
然后再调用Pattern.matches并包含其他函数调用(因为matches
将正则表达式作为输入 - 正则表达式编译会产生额外的开销。< / p>
虽然matches
也接受正则表达式,但它有自己的加分
答案 1 :(得分:0)
区别在于
x.equals((String)null)
在
时返回false
x.compareTo((String)null) == 0
抛出NullPointerException
。所以即使对于弦乐来说,它们也不总是可以互换的。
你可以找到here什么是更好的表现
string stringToTest = "Hello";
stringToTest.Equals("hello", StringComparison.OrdinalIgnoreCase);
等于时间:00:00:00.0009247
String.Compare(stringToTest, "hello", StringComparison.OrdinalIgnoreCase);
比较计时器:00:00:00.0000012
你可以用
检查javaimport java.util.Date;
import java.util.*;
public class HelloWorld{
public static void main(String []args){
String Str1 = new String("This is really not immutable!!");
String Str2 = Str1;
String Str3 = new String("This is really not immutable!!");
boolean retVal;
long millis = System.nanoTime();
retVal = Str1.equals( Str2 );
System.out.println("Returned Value = " + retVal );
retVal = Str1.equals( Str3 );
System.out.println("Returned Value = " + retVal );
long millis1 = System.nanoTime();
System.out.println("time to equals " + (millis1-millis) );
int ret = Str1.compareTo( Str2 );
System.out.println("Returned Value = " + ret );
ret = Str1.compareTo( Str3 );
System.out.println("Returned Value = " + ret );
System.out.println("Hello World");
Date d2 = new Date();
long millis2 = System.nanoTime();
System.out.println("time to compareTo " + (millis2-millis1) );
}
}
并获得输出:
Returned Value = true
Returned Value = true
time to equals 189893
Returned Value = 0
Returned Value = 0
Hello World
time to compareTo 692090
所以是的,等于似乎更快