Some quick notes on converting String operations to use Span
I was asked on
Twitter , regarding
String Resource Visualizer, whether "using Span
for string operations [will] make it faster?"
My inclination was that potentially it would, but at a cost of code readability and I wasn't sure if it really needed the optimization.
Also, I'd read a bit about Span<T> when it was first announced and it all seemed very complicated and abstract. I assumed that it was more for low-level things and I could happily ignore it.
It nagged me though that the String Resource Visualizer was doing a lot every time the text of the editor window changed in VS. Yes, every time the screen is scrolled or the text changes. That's a LOT! In theory, any perf improvements would be a good thing as they could improve the UI responsiveness of Visual Studio. If someone had a slow or low-powered machine this could be important.
Today I had some time on my hands while installing some updates over my disappointingly slow internet connection. So I did some more research on Span<T>.
It turns out it's not as complicated as I thought so I decided it was worth investigating what, if any, improvement could be made from the change.
Because the actual code has some coupling that doesn't lead to easy benchmarking, I created a version of the important part of the code in a separate, console, app.
I then created another version that used ReadOnlySpan<char> instead of a string as much as possible.
All the code is here.
Cutting to the chase, here are the results of the benchmark test.
Or if the image is hard to see, here are the important numbers
Method | Mean | Error | StdDev |
-------------- |---------:|----------:|----------:|
UsingString | 67.65 us | 0.4932 us | 0.4372 us |
UsingSpanChar | 40.85 us | 0.1412 us | 0.1321 us |
Not using string was about one-third faster, but that's only approx. 27 microseconds.
Proportionally that's a lot but in real terms, not so much.
I'm left torn.
- Making the code faster could be really important given that it potentially runs on every keystroke.
- It's not a lot of time though and no-one is complaining about performance. Could this be an unnecessary micro-optimization?
- There are other parts of the code when a definite performance improvement could be made by reducing IO. This seems a higher priority.
- Having spent years writing code that does string manipulation, I'm not yet ready to jump into making changes that will affect the readability of the code.
I'm going to wait and reflect on this before deciding what to do next.
0 comments:
Post a Comment
I get a lot of comment spam :( - moderation may take a while.