Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I implement StringBuilder and/or call String.FastAllocateString?

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.

  • Anyone know a secret ninja alternative way to call FastAllocateString?
  • Anyone know what ForceTokenStabilization really does (and possibly an alternative way to achieve it?)
like image 874
Jay Sullivan Avatar asked Nov 15 '13 01:11

Jay Sullivan


1 Answers

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!
//===========================================================================================================
like image 183
Simon Whitehead Avatar answered Oct 29 '22 09:10

Simon Whitehead