What's the quickest way to compare strings in Java?

后端 未结 7 2059
情话喂你
情话喂你 2020-12-06 04:42

What\'s the quickest to compare two strings in Java?

Is there something faster than equals?

EDIT: I can not help much to clarify the problem.

I have

相关标签:
7条回答
  • 2020-12-06 05:09

    I had tries different combinations for string comparison (code here):

    1. s1.equals(s2)
    2. s1.length() == s2.length() && s1.hashCode() == s2.hashCode() && s1.equals(s2)
    3. s1.hashCode() == s2.hashCode() && s1.equals(s2);
    4. s1.length() == s2.length() && s1.equals(s2);
    

    I used strings of 40 chars length, in 10000000000L iterations and before any iteration I reinitialized the strings.

    for equal stings I got:

    equal: 2873 milis ???
    equal: 21386 milis
    equal: 7181 milis
    equal: 2710 milis ???
    

    for same size strings but last char different I got:

    different: 3011 milis
    different: 23415 milis
    different: 6924 milis
    different: 2791 milis
    

    for different sizes, almost same strings but one char added at the end for s2:

    different size: 3167 milis
    different size: 5188 milis
    different size: 6902 milis
    different size: 2951 milis
    

    seems to me it is best to use first a string.length() comparison before equals().

    But this will not matter almost at all because this is the case where I have 10^10 string comparisons with 40 chars length and what is bizarre for me is the case where for equal strings I have a better speed when I compare the string length first.

    0 讨论(0)
提交回复
热议问题