Krishna Kumar Krishna Kumar - 4 years ago 96
Java Question

Is "startsWith" faster than "indexOf"?

I am writing code in Java where I branch off based on whether a

string
starts with certain characters while looping through a
dataset
and my
dataset
is expected to be large.

I was wondering whether
startsWith
is faster than
indexOf
. I did experiment with 2000 records but not found any difference.

Answer Source
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 startsWith seems to be better, for obvious reason that it doesn't have to traverse through string. But in best case scenario both should perform close while in a worst case scenario startsWith will always perform better than indexOf

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download