Skip to content

Avoid creating unnecessary intermediate strings #3415

Closed
@paulomorgado

Description

@paulomorgado

Describe the feature

I found in the code base code like this:

            using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture))
            {
                // ...
                string snippet = stringWriter.ToString();
                request.Content = System.Text.Encoding.UTF8.GetBytes(snippet);
            }

StringWriter uses an internal StringBuilder that will be used to produce a string just to get the utf-8 bytes.

Use Case

Creating objects that do not need to be created, not only uses memory and CPU to create them, but also causes GC work.

Proposed Solution

Consider using a StreamWriter instead:

using (var ms = new MemoryStream())
{
    using (var writer = new new StreamWriter(ms))
    {
       // ...
    }
    request.Content = ms.ToArray();
}

Other Information

If IRequest.Content was a ArraySegment<byte>, this:

request.Content = ms.ToArray();

coulde be this:

request.Content = new ArraySegment<byte>(ms.GetBuffer(), 0, (int)ms.Length);

which is one less byte[] allocation.

Acknowledgements

  • I may be able to implement this feature request
  • This feature might incur a breaking change

AWS .NET SDK and/or Package version used

AWSSDK.KeyManagementService 3.7.300.52

Targeted .NET Platform

.NET 8

Operating System and version

Windows and Linux

Metadata

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