如何实现StringBuilder和/或调用String.FastAllocateString?

Jay*_*van 10 .net c# stringbuilder cil

我很好奇,看看我是否可以创建一个优化版本StringBuilder(以便加速一点,因为它目前是我的一个应用程序的瓶颈).对我来说不幸的是,它似乎使用了我无法使用的"神奇"系统调用(或者看起来似乎如此).

在反编译源代码后System.Text.StringBuilder,我注意到它使用了以下内部(因此不可调用)系统调用:

[SecurityCritical]
[MethodImpl(MethodImplOptions.InternalCall)]
internal static string FastAllocateString(int length);
Run Code Online (Sandbox Code Playgroud)

这个未记录的属性也被大量使用:

[ForceTokenStabilization]
Run Code Online (Sandbox Code Playgroud)

我能够FastAllocateString(n)用just 替换所有调用String.Empty并注释掉所有[ForceTokenStabilization]属性.执行此操作后,从其他类复制粘贴一些方法,我实际上能够编译它.(完整代码).

我真的很想不必做出这两个权衡,因为我认为他们是有原因的.

  • 有人知道一个秘密的忍者替代方式来打电话FastAllocateString吗?
  • 任何人都知道ForceTokenStabilization真正做了什么(可能还有另一种方法来实现它?)

Sim*_*ead 10

你可以称之为:

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
Run Code Online (Sandbox Code Playgroud)

请注意,FastAllocateString是成员string..

Rotor SSCLI发行版在内部为运行代码的平台发出本机ASM,以分配缓冲区并返回地址.我只能假设官方CLR大致相同.

根据此链接,ForceTokenStabilization适用于:

//===========================================================================================================
// [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!
//===========================================================================================================
Run Code Online (Sandbox Code Playgroud)

  • 你想要肯定地缓存`MethodInfo`.即便如此,我想知道你是不是更快只是调用`new string('\ 0',20)`而不是通过`MethodInfo`来调用`FastAllocateString`. (3认同)
  • @Simon Whitehead:谢谢你的答案,但如果它是你的应用程序的瓶颈,那么它不是过早的优化.而Jon Hanna是对的,这可能不会很"快" (2认同)