I was having a look at the Equals
method implementation of the String
class of the .NET framework and found that it uses the EqualsHelper
method. I found that it's really a very cool and efficient method, but there's something very weired I f开发者_如何学Pythonound, why do they increment the pointers (or making offsets) via a division operation, like:
*(long*)(ptr + (IntPtr)8 / 2), ptr += (IntPtr)4 / 2;
and so on.
Thanks!
Ah, the reason I didn't see what you were talking about is that you're looking at the 64-bit sources, rather than the 32-bit sources, as I was originally.
It turns out that the original source code file has an #if
directive in it. It does different things depending on whether or not the AMD64
symbol is defined at compile time.
The comments in the original code are quite instructive. Basically, when compiling the framework for 64-bit platforms, they've chosen to unroll the loop by 12 and check 3 quadwords at a time. This is a performance optimization that is made possible by the different system architecture.
// unroll the loop
#if AMD64
// for AMD64 bit platform we unroll by 12 and
// check 3 qword at a time. This is less code
// than the 32 bit case and is shorter pathlength
while (length >= 12)
{
if (*(long*)a != *(long*)b) break;
if (*(long*)(a+4) != *(long*)(b+4)) break;
if (*(long*)(a+8) != *(long*)(b+8)) break;
a += 12; b += 12; length -= 12;
}
#else
while (length >= 10)
{
if (*(int*)a != *(int*)b) break;
if (*(int*)(a+2) != *(int*)(b+2)) break;
if (*(int*)(a+4) != *(int*)(b+4)) break;
if (*(int*)(a+6) != *(int*)(b+6)) break;
if (*(int*)(a+8) != *(int*)(b+8)) break;
a += 10; b += 10; length -= 10;
}
#endif
If you're interested in the internals of the .NET Framework, make sure to download the full version of the shared source from this site. You miss a lot of interesting things when you're trying to do it using only .NET Reflector. Not the least of which is the comments. And to think, I've seen people argue on here that comments aren't necessary in well-written code!
精彩评论