Java Performance中的String.compareTo()vs String.matches()

时间:2013-09-15 07:42:35

标签: java string string-comparison

比较字符串时,其中一种方法是否有任何优势?

2 个答案:

答案 0 :(得分:1)

未使用数据集进行测试,但检查compareTomatches的源代码  似乎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

你可以用

检查java
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

所以是的,等于似乎更快