As you can tell, this is some funky stuff! As this is a performance critical method (comparing strings is a pretty common task, obviously), the implementers have gone all pointery. There are several things to note here:
- The fixed keyword at lines 8-9: it tells the GC to leave our strings alone and not move them around while we’re using the pointers to them. Pointers won’t do much good if the managed objects are moved in the heap before the comparison is done.
- The beautiful while loop at line 13 compares 20 bytes at a time (int = 4 bytes and we’re looking at 5 integers at a time). When we’re at the last 20 bytes, we do 4 bytes at a time. I assume this rather weird method of comparing is faster, perhaps due to less pointer increments/decrements. If one of you hackers would like to explain, that would be awesome.
- One might wonder, since a char = 2 bytes, and we’re looking at 4 bytes at a time at a minimum, how come this method works on strings with an odd length? Well, our current guess is that since the string is null terminated in memory, we either compare the null char (for odd strings) or not (for even strings). Either way – it shouldn’t matter to the result, we can always assume an even amount of characters. This assumption would of course not work for strings in different lengths, but lines 5-7 take care of that for us. (This my colleague Yuval Pinter’s insight. Thanks!)
Like I said, funky stuff.