Repository navigation
Avoid heap allocating in char.ConvertFromUtf32 - #6141
Conversation
There was a problem hiding this comment.
Nit: Might as well fix the misspelling while making changes here: sumplementary -> supplementary
There was a problem hiding this comment.
I do not think that the comment about stackalloc is relevant here. It would be generally better to allocate the space as uint here regardless - given how the optimizations that the JIT is capable of.
A different problem is that dotnet/coreclr#5719 is pretty confused. I do not think it is a real problem. I have just added a comment to it. We have been using stackalloc for years for unsafe perf optimizations with pretty clear results.
|
I always have mixed feelings about optimizing rare paths, in slow convenience methods, using unsafe code. It is asking for security bug to sneak in. Given that char is low level type, this one is probably ok. |
There was a problem hiding this comment.
Also, the method needs to be marked with SecuritySafeCritical critical attribute now because of it contains unsafe code.
|
Could you please port the change to CoreRT as well? |
|
Thanks! |
Currently
char.ConvertFromUtf32creates a new char array of length 2, modifies it, and then creates a string out of that. This is a bit wasteful, since it means an extra heap allocation that won't be used by the caller. This changes that to allocate 2 chars' worth of space on the stack via declaring a localuint, then taking the address of that, modifying it, and passing it into thestring(char*, int, int)constructor.I didn't use
stackallochere since from my benchmarks it seems to be a bit slower than declaring a local variable; see results for heap, stackalloc, and local uint (here is the source code). Also note that since most of the overhead in those timings is probably allocating/calling the string ctor, the differences may be greater than they reflect.Separated out from #4881 (which should probably be merged sometime)
cc @jkotas