(str) String.equals is inefficient. Unrolling comparison loop makes it faster

XMLWordPrintable

    • Type: Enhancement
    • Resolution: Won't Fix
    • Priority: P4
    • None
    • Affects Version/s: 1.3.1
    • Component/s: core-libs
    • generic
    • generic

      Name: bsT130419 Date: 10/12/2001


      java version "1.3.1_01"
      Java(TM) 2 Runtime Environment, Standard Edition (build 1.3.1_01)
      Java HotSpot(TM) Client VM (build 1.3.1_01, mixed mode)

      The loop for String.equals is not very efficient. It can be
      made 40% faster for strings longer than 4 characters by
      unrolling it four times. Even though this incurs a slight
      performance penalty for comparison of strings shorter than
      4 characters, it seems worth it overall. Here is the new
      code:

      public boolean equals( Object anObject )
      {
        if (anObject == this)
          return true;

        if (anObject instanceof String1)
        {
          String1 other = (String1) anObject;
          int n = count;
          if (n == other.count)
          {
            char[] v1 = value;
            char[] v2 = other.value;
            int i = offset;
            int j = other.offset;

            while (n >= 4)
            {
              if (v1[i] != v2[j] || v1[i+1] != v2[j+1] ||
                  v1[i+2] != v2[j+2] || v1[i+3] != v2[j+3])
                return false;

              i += 4;
              j += 4;
              n -= 4;
            }

            while (n-- >= 1)
              if (v1[i++] != v2[j++])
                return false;

            return true;
          }
        }

        return false;
      }
      (Review ID: 133604)
      ======================================================================

      No description of the performance test method or platform was given.

      ###@###.### 2001-10-12

            Assignee:
            Jim Gish (Inactive)
            Reporter:
            Bill Strathearn (Inactive)
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

              Created:
              Updated:
              Resolved:
              Imported:
              Indexed: