Skip to content

Commit

Permalink
Optimize allocations in TextReader.ReadToEnd utilized by SourceText.F…
Browse files Browse the repository at this point in the history
…rom (#70017)

* Optimize allocations in TextReader.ReadToEnd utilized by SourceText.From

The profile I'm looking currently shows 9.4% of allocation in our codeanalysis process under SourceText.From. These allocations occur during the TextReader.ReadToEnd call. Fortunately, Roslyn is already passing in a TextReader that knows it's length, and thus we can optimize this path.

In netfx, this should at least get rid of the extra sizing allocations done during TextReader.ReadToEnd as it appends to it's internal stringbuilder. So, this should see a reduction of about 20% of the allocations in this codepath.

In netcore (which is the case for this profile), we do better as this essentially gets rid of all allocations except for the equivalent of the StringBuilder.ToString call. So, this should see a reduction of about 2/3 of the allocations of this codepath.
  • Loading branch information
ToddGrun authored Sep 20, 2023
1 parent 1421a4a commit f455ada
Showing 1 changed file with 13 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,25 @@
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#nullable disable

using System.IO;

namespace Microsoft.CodeAnalysis.Shared.Utilities
{
internal abstract class TextReaderWithLength(int length) : TextReader
{
public int Length { get; } = length;

public override string ReadToEnd()
{
#if NETCOREAPP
return string.Create(Length, this, static (chars, state) => state.Read(chars));
#else
var chars = new char[Length];

var read = base.Read(chars, 0, Length);

return new string(chars, 0, read);
#endif
}
}
}

0 comments on commit f455ada

Please sign in to comment.