Java – “startswith” is faster than “indexof”?

I write code in Java to cycle through the dataset at the same time according to whether the string starts with some characters, and my dataset is expected to be large

I wonder if startswith is faster than indexof I did test 2000 records, but I didn't find any difference

Solution

public class Test
public class Test
{
  public static void main(String args[]) {

    long value1 = System.currentTimeMillis();
    for(long i=0;i<100000000;i++)
    {
        "abcd".indexOf("a");
    }
    long value2 = System.currentTimeMillis();
    System.out.println(value2-value1);


    value1 = System.currentTimeMillis();
    for(long i=0;i<100000000;i++)
    {
        "abcd".startsWith("a");
    }
    value2 = System.currentTimeMillis();
    System.out.println(value2-value1);
  }
}

It seems better to test it and perf for starts with this code, because it obviously doesn't need to traverse the string But in the best case, both should perform shutdown, and in the worst case, start and always perform better than indexof

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>