Skip to content

Make string.FastAllocateString public #36989

Closed
@vanbukin

Description

Background and Motivation

Provide ability for developers to write libraries that able to format something to string using pre-allocated pinned char* pointer withoput any overhead for delegate call.
It's also possible now to "export" that function using .ilproj like this, but it works only with undocumented IgnoresAccessChecksToAttribute

Proposed API

namespace System
{
-    internal static extern string FastAllocateString(int length);
+    public static extern string FastAllocateString(int length);
}

Usage Examples

Preallocate known-size string, get pinned char* pointer and overwrite string contents like here or here

public string ToString(string? format, IFormatProvider? formatProvider)
{
   // ...
   public string ToString(string? format, IFormatProvider? formatProvider)
   {
       // ...
        var uuidString = string.FastAllocateString(32);
        fixed (char* uuidChars = &uuidString.GetPinnableReference())
        {
            FormatN(uuidChars);
        }
        return uuidString;
       // ...
   }
   // ...
}

Alternative Designs

Provide separate external library (do not ship it with System.Private.CoreLib), that expose that method with public modifier or add string.Create overload without delegate that can only allocate and return string.

Risks

That API should be supported in a future versions of .NET

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions