Better lazy initialization for Encoding static properties#6890
Conversation
There was a problem hiding this comment.
It is wasteful to create new holder types for these - even trivial type costs 100's bytes at runtime. It would better to make these readonly variables in the respective encoding types:
public class ASCIIEncoding
{
internal readonly ASCIIEncoding Instance = new ASCIIEncoding();
...
Similar pattern is used in number of places in coreclr and corefx.
There was a problem hiding this comment.
@jkotas I saw your suggestion in the other issue, however I did not follow it for reasons of code cleanliness (people might wonder why there is a static field being used nowhere in the file).
Perhaps what I'll do is make all the Encoding subclasses partial, and then have a file like Encoding.StaticProperties.cs (probably with a better name) and keep all of the static property-initialization logic in there. That way, the comment will not have to be repeated per-Encoding, and there won't be a need for all of these new classes.
There was a problem hiding this comment.
I do not see a problem with internal static field that is not used anywhere else in the file. It is pretty common with the existing uses of this pattern.
One example out of many:
There was a problem hiding this comment.
@jkotas Yeah, but the example you pointed out is a singleton. UTF8Encoding on the other hand has a public constructor, so naming it Instance or s_instance will be confusing since you can create multiple instances of it.
There was a problem hiding this comment.
It can be called DefaultInstance
1930402 to
5976ffa
Compare
|
@jkotas I have made the changes you suggested; thanks for reviewing. (I used |
There was a problem hiding this comment.
This generates warnings:
warning CS0108: 'ASCIIEncoding.Default' hides inherited member 'Encoding.Default'. Use the new keyword if hiding was intended.
There was a problem hiding this comment.
readonly field would have same effect, with more compact IL...
01ec3de to
66d9c20
Compare
|
Test Windows_NT x64 Release Priority 1 Build and Test |
|
Thanks! |
…eclr#6890) Better lazy initialization for Encoding static properties Commit migrated from dotnet/coreclr@df50db7
Previously the Encoding properties were not being inlined and made use of volatile fields, which are particularly costly on ARM (I think). This changes them to use nested static classes instead, which are a better way to perform lazy initialization (#1193) since we bypass checks if the cctor has already been run.
Partially addresses #6759
Unfortunately this only made a small impact (< 10%, maybe 6-8%) for cases like
since Encoding is basically a landmine of virtual method calls. However the difference is still there, and the diff is mainly red.
cc: @jkotas @omariom