Replace and remove whitespaces in strings - performant and sustainable
There are many ways to remove spaces or other characters in a string - there are just very big differences in terms of performance and efficiency.
Benchmark
As part of my Sustainable Code Repository, I have created various code snippets to simulate everyday coding situations. I used regex, string operations and the relatively new Span API. I deliberately left out vectorization, e.g. with the help of Vector128, which will be the most performant solution. Vector128 is highly optimized, but not an everyday solution.
Code
So I have created a code that uses an input to remove spaces in various ways.
Benchmark
I then used benchmarking to measure this code.
You can see some enormous differences; StringBuilder, which is actually so performant in many situations, is much slower and generates many more allocations. Regex, on the other hand, is not as bad as you might think. But as you would expect, the various Span variants are all very far ahead in terms of performance - so it's good that the new Span API is really easy to understand and use.
However, if you need the very best performance, you won't be able to avoid using AVX2, for example meziantou's Replace characters in a string using Vectorization implementation.
Sustainable Code
You can find this and many more examples on my GitHub under Sustainable Code.