Replies: 3 comments 1 reply
-
There is a little problem here: How would ReadLineAsSpan() be able to signal end of the string being reached vs. reading an empty line? This is not correct: As a span type (ref struct) can't be wrapped in Nullable<T> nor be used in a value tuple, you would either need to introduce a boolean out parameter (or something similar) or use |
Beta Was this translation helpful? Give feedback.
-
Yeas I understand the issue with nullable, and I thought exactly the same thing and had the same concern about design rules. So I checked the first few results on Bing 😉 to see how people use
To be honest, I don’t like any of these patterns (of course, this is just a style preference):
I suggest providing a better API by creating a method (I’m not sure if
You can then use
When the end of the string is reached, it would work in the same way as ReadLine. ReadLine will return null indefinitely, just like ReadLineAsSpan would indefinitely return an empty span. Here are the proposed minimal changes:
|
Beta Was this translation helpful? Give feedback.
-
I've run a benchmark for code above and I got results as below. ReadLineAsSpan would result in almost no allocation and 30% speed improvement.
|
Beta Was this translation helpful? Give feedback.
Uh oh!
There was an error while loading. Please reload this page.
-
I am considering the addition of a ReadLineAsSpan method to the StringReader class. The current
ReadLine
method returns a string, likely for backward compatibility reasons. However, this approach seems to undermine the benefits of using spans within theStringReader
class.When reading a string line by line, the current implementation reallocates the entire string in chunks, which could be avoided by returning a ReadOnlySpan instead.
With minimal modifications, the existing method
public override string? ReadLine()
would becomepublic ReadOnlySpan<char> ReadLineAsSpan()
and newReadLine()
would be createdAnd previous
public override string? ReadLine()
becomesThis approach maintains backward compatibility while leveraging the performance benefits of spans.
Does this proposal make any sense? Am I missing something?
Beta Was this translation helpful? Give feedback.
All reactions