diff --git a/src/libraries/System.Console/src/System/IO/StdInReader.cs b/src/libraries/System.Console/src/System/IO/StdInReader.cs index 3929dda532c32..f44fd7d47ded1 100644 --- a/src/libraries/System.Console/src/System/IO/StdInReader.cs +++ b/src/libraries/System.Console/src/System/IO/StdInReader.cs @@ -46,11 +46,15 @@ internal bool IsUnprocessedBufferEmpty() internal void AppendExtraBuffer(ReadOnlySpan buffer) { - // Ensure a reasonable upper bound applies to the stackalloc - Debug.Assert(buffer.Length <= 1024); - - // Then convert the bytes to chars - Span chars = stackalloc char[_encoding.GetMaxCharCount(buffer.Length)]; + // Most inputs to this will have a buffer length of one. + // The cases where it is larger than one only occur in ReadKey + // when the input is not redirected, so those cases should be + // rare, so just allocate. + const int MaxStackAllocation = 256; + int maxCharsCount = _encoding.GetMaxCharCount(buffer.Length); + Span chars = (uint)maxCharsCount <= MaxStackAllocation ? + stackalloc char[MaxStackAllocation] : + new char[maxCharsCount]; int charLen = _encoding.GetChars(buffer, chars); chars = chars.Slice(0, charLen);