mongodb/mongo-csharp-driver — pull request #94 by optimiz3 (2012-04-13 21:25:11+00:00)
Title: Improve BSON deserialization performance.

When reading large amounts of data BsonBuffer.ReadCString is one of the top two most CPU costly functions. This is because 3 passes have to happen over the input data:

1. Array.IndexOf to find the null character
2. Encoding.GetString
a. UTFEncoding.GetCharCount (internally) to size the string
b. UTFEncoding.GetChars (internally) to populate the string

CStrings are almost exclusively used for BSON field names, meaning they are almost always short ASCII strings:

By leveraging step 1 to detect if the string is ASCII only, we can use ASCIIEncoder to reduce step 2a from O(N) to O(1) when the string is ASCII only.

While in theory step 2 could be eliminated if we did direct conversion during step 1, this would require a temporary char[] array because .Net does not permit strings to be modified directly (resulting in another copy), thus negating the benefit.