Wednesday, January 30, 2008

Playing with the .NET FCL symbols and source code

I’m playing with the debug symbols for the .NET framework and came across some interesting things in code.

Dropping back to memory manipulation for performance from the String class

// Returns the entire string as an array of characters.

unsafe public char[] ToCharArray() {

// huge performance improvement for short strings by doing this

int length = Length;

char[] chars = new char[length];

if (length > 0)

{

fixed (char* src = &this.m_firstChar)

fixed (char* dest = chars)

wstrcpyPtrAligned(dest, src, length);

}

return chars;

}

AMD Specific code!

#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