Search Unity

Comparing strings: No difference when using GetHash()?

Discussion in 'Scripting' started by Shack_Man, Mar 22, 2019.

  1. Shack_Man

    Shack_Man

    Joined:
    Jun 7, 2017
    Posts:
    372
    I've been reading how bad strings and string comparisons are due to memory allocation. Since I have a lot of collisions that compare tags, I tried using hashcodes, but I can't see any difference, even in this code where I am comparing them 10000 times per frame:

    Is my code wrong or doesn't it make any difference on desktop anyway? I added the x = 0 since I wasn't sure if the comparison gets compiled if there is nothing in it?

    Code (CSharp):
    1. public class HashTest : MonoBehaviour
    2. {
    3.  
    4.     private string string1 = "Hello", string2 = "Bye";
    5.     int hashcode1, hashcode2, x;
    6.  
    7.     public bool useHashcode;
    8.  
    9.  
    10.     private void Start()
    11.     {
    12.         hashcode1 = string1.GetHashCode();
    13.         hashcode2 = string2.GetHashCode();
    14.     }
    15.  
    16.  
    17.     private void Update()
    18.     {
    19.         if (useHashcode)
    20.             CompareStringsViaHash();
    21.         else
    22.             CompareStrings();
    23.     }
    24.  
    25.  
    26.  
    27.  
    28.  
    29.     void CompareStrings()
    30.     {
    31.         for (int i = 0; i < 10000; i++)
    32.         {
    33.             if (string1 == string2)
    34.             {
    35.                 x = 0;
    36.             }
    37.  
    38.         }
    39.  
    40.     }
    41.  
    42.     void CompareStringsViaHash()
    43.     {
    44.         for (int i = 0; i < 10000; i++)
    45.         {
    46.             if (hashcode1 == hashcode2)
    47.             {
    48.                 x = 1;
    49.             }
    50.         }
    51.  
    52.     }
    53. }
     
  2. palex-nx

    palex-nx

    Joined:
    Jul 23, 2018
    Posts:
    1,748
    That's because .net already have this optimization built-in. And a few more. And your strings are not equal. Try to compare against equal strings. Hash equality does not mean strings are equal too, but when hashes are not equal then strings are not equal too. Also, to see the actual difference your comparands needs to be much longer like thousands of chars or more, not just "Hello".
     
    Shack_Man, Ryiah and halley like this.