-6

比较字符串时,其中一种方法比另一种方法有什么优势吗?

4

2 回答 2

1

未使用数据集进行测试,但检查compareTo匹配的源代码 似乎compareTo会更快,因为matches然后再次调用Pattern.matches并包括其他函数调用(因为matches将正则表达式作为输入 - 正则表达式编译会产生额外的开销。

虽然因为matches它也接受正则表达式,但它有自己的加分

于 2013-09-15T08:43:33.270 回答
0

不同之处在于

x.equals((String)null)

返回false

x.compareTo((String)null) == 0

抛出一个NullPointerException. 因此,即使对于字符串,它们也不总是可以互换的。

你可以在这里找到更好的表现

string stringToTest = "Hello";
stringToTest.Equals("hello", StringComparison.OrdinalIgnoreCase);

等于时间:00:00:00.0009247

String.Compare(stringToTest, "hello", StringComparison.OrdinalIgnoreCase);

比较计时器:00:00:00.0000012

你可以用

import 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

所以是的,equals 似乎更快

于 2013-09-15T07:47:33.480 回答