Is "StartsWith" faster than "indexOf"?

I write code in Java, where I disconnect based on whether it starts stringwith certain characters when the loop datasetand mine are datasetexpected to be big.

I was wondering if it was faster startsWith indexOf. I experimented with 2,000 entries, but did not find the difference.

+3
source share
7 answers
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);
  }
}

Tested it with this piece of code and perf for startWith seems to be better, for the obvious reason that it does not need to go through a line. But in the best case scenario, the script should run close, while in the worst case scenario, startWith will always work better than indexOf

-2
source

startsWith - , .

, 2000 ( ). , , , . , 10-30 , , , . ( , , , . - .)

, . indexOf startsWith , indexOf 0. , , . ( , , , -, .)

+9

, -:

", ".

, , .

, . (startsWith, ). , , , . . ; -)

, , startWith, , indexOf. , . (, startsWith indexOf)

+6

, , startsWith , , :

a.startsWith(b) b. , b , .

a.indexOf(b) ( ). a. , , , , .

, , , . .

+5

, , , indexOf .

+2

, indexOf == 0.

, ?

+1

, . , . , . , startWith, , , , , , .

0

Source: https://habr.com/ru/post/1711552/


All Articles