Improve perf of Encoding.GetEncoding(int) (#6907)
authorJustin Van Patten <jvp@justinvp.com>
Thu, 25 Aug 2016 18:54:11 +0000 (11:54 -0700)
committerJan Kotas <jkotas@microsoft.com>
Thu, 25 Aug 2016 18:54:11 +0000 (11:54 -0700)
commit24918bf5e4bd94547b994a3a3f8d565e972eeac6
treede3c08083e8e36dfc4b106eea6971f98f7f92970
parent4f0fbd0cbb8606055b222300d68ecd2f44ee2ca4
Improve perf of Encoding.GetEncoding(int) (#6907)

`Encoding.GetEncoding(int)` caches encoding instances in a `Hashtable`.
This involves locking and boxing the codepage (potentially multiple
times). For the encodings that are already cached in static fields
(e.g. UTF8, Unicode, ASCII, etc.), this is unnecessary overhead --
these instances do not need to be stored in the `Hashtable` because
they are already stored in static fields.

It turns out the only instance that would be stored in the
`Hashtable` in CoreCLR is UTF32BE. Thus, on CoreCLR, we can remove the
use of the `Hashtable` altogether, and instead store the UTF32BE
instance in a static field. This means the `Hashtable` static field,
lock object, and box allocations go away entirely on CoreCLR.

We now check for the encodings that can be cached in static fields in a
switch statement up-front. On Desktop, it then falls back to doing the
`Hashtable`-based lookup/storage, and only boxes codepage once.
src/mscorlib/src/System/Text/Encoding.cs
src/mscorlib/src/System/Text/UTF32Encoding.cs