From bf7a89cb0545b1c1f8d003770b7e8c71786f1ecb Mon Sep 17 00:00:00 2001 From: stephentoub Date: Wed, 7 Oct 2015 12:48:53 -0400 Subject: [PATCH] Reduce garbage generated in StringBuilder marshaling When marshaling a StringBuilder In as Ansi (both done by default on Unix), we currently allocate enough native memory to hold the result. But then we use AnsiCharMarshaler.DoAnsiConversion to allocate a managed byte array and fill it with the converted results, and then we copy those results into the native memory. We can instead just call String's ConvertToAnsi directly, avoiding the extra managed array allocation and the extra memory copy. --- src/mscorlib/src/System/StubHelpers.cs | 17 ++++------------- 1 file changed, 4 insertions(+), 13 deletions(-) diff --git a/src/mscorlib/src/System/StubHelpers.cs b/src/mscorlib/src/System/StubHelpers.cs index 7875f2d..e955203 100644 --- a/src/mscorlib/src/System/StubHelpers.cs +++ b/src/mscorlib/src/System/StubHelpers.cs @@ -1056,20 +1056,11 @@ namespace System.StubHelpers { if (IsIn(dwFlags)) { - int length; - - byte[] bytes = AnsiCharMarshaler.DoAnsiConversion( - pManagedHome.ToString(), + int length = pManagedHome.ToString().ConvertToAnsi( + ptr, allocSize, IsBestFit(dwFlags), - IsThrowOn(dwFlags), - out length); - - Buffer.Memcpy( - ptr, // dst buffer - 0, // dts index - bytes, // src array - 0, // src index - length); // len + IsThrowOn(dwFlags)); + Contract.Assert(length < allocSize, "Expected a length less than the allocated size"); // null-terminate the native string *(ptr + length) = 0; -- 2.7.4