I was curious to see if I could create an optimized version of StringBuilder
(to take a stab at speeding it up a little, as it is currently the bottleneck of one of my applications). Unfortunately for me, it seems to make use of "magical" system calls that are not available for me to use (or so it seems).
After decompiling the source code for System.Text.StringBuilder
, I noticed it makes use of the following internal (and therefore uncallable) system call:
[SecurityCritical]
[MethodImpl(MethodImplOptions.InternalCall)]
internal static string FastAllocateString(int length);
There's also this undocumented attribute that gets used a lot:
[ForceTokenStabilization]
I was able to replace all calls to FastAllocateString(n)
with just String.Empty
and comment out all [ForceTokenStabilization]
attributes. After doing this, and copy-pasting some methods from other classes, I was actually able to get it to compile. (complete code).
I'd really like to not have to make these two tradeoffs, because I assume they are there for a reason.
FastAllocateString
? ForceTokenStabilization
really does (and possibly an alternative way to achieve it?)You can call it:
var fastAllocate =
typeof (string).GetMethods(BindingFlags.NonPublic | BindingFlags.Static)
.First(x => x.Name == "FastAllocateString");
var newString = (string)fastAllocate.Invoke(null, new object[] {20});
Console.WriteLine(newString.Length); // 20
Note that FastAllocateString
is a member of string
..
The Rotor SSCLI distribution internally emits native ASM for the platform the code is running on to allocate a buffer and return the address. I can only assume the official CLR is roughly doing the same.
According to this link, ForceTokenStabilization
is for:
//===========================================================================================================
// [ForceTokenStabilization] - Using this CA forces ILCA.EXE to stabilize the attached type, method or field.
// We use this to identify private helper methods invoked by IL stubs.
//
// NOTE: Attaching this to a type is NOT equivalent to attaching it to all of its methods!
//===========================================================================================================
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With