Reduce garbage generated in StringBuilder marshaling
authorstephentoub <stoub@microsoft.com>
Wed, 7 Oct 2015 16:48:53 +0000 (12:48 -0400)
committerstephentoub <stoub@microsoft.com>
Wed, 7 Oct 2015 17:05:22 +0000 (13:05 -0400)
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

index 7875f2d..e955203 100644 (file)
@@ -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;