Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

c# - A look inside the EqualsHelper method in the .NET framework

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 found, 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!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...