Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Cover image for Improving String Manipulation in .NET
Vanderlei Adriano Morais
Vanderlei Adriano Morais

Posted on

     

Improving String Manipulation in .NET

One thing so trivial as transforming a string could have considerable impact in the performance depending on how is implemented. Let's check an example of a simple requirement that I had to work some time ago.

The Requirement

Given a "CPF" (Brazilian National ID) stored as string with only numeric digits, add some standard separators (“.” and “-”) to display it in a more user-friendly format, pretty straightforward as:

> Input: “12345678909”  > Output: “123.456.789–09”
Enter fullscreen modeExit fullscreen mode

Initial Solution: Stack Overflow

Like a good developer I google it for a quick solution and, of course, I ended up in Stack Overflow. In the best voted answer, I found this implementation:

publicstringFormat(stringcpf){returnConvert.ToUInt64(cpf).ToString(@"000\.000\.000\-00");}
Enter fullscreen modeExit fullscreen mode

Looks like a good solution, right? To use the number format string - that allows defining a mask for a number in theToString method - the string was converted toUInt64.

Pretty clever, huh? Not much...

My Solution

I had doubts about the performance of the solution found, especially because the conversion part, so I tried to implement my own solution in a very simple way:

publicstringFormat(stringcpf){return$"{cpf.Substring(0,3)}.{cpf.Substring(3,3)}.{cpf.Substring(6,3)}-{cpf.Substring(9,2)}";}
Enter fullscreen modeExit fullscreen mode

Basically, I just usedSubstring to split the CPF into four parts, inserting the corresponding separators.

Then, to compare the approaches I usedBenchmark.DotNet, here are the results:

MethodMeanRatio
FormatCpfConvert301.97 nsbaseline
FormatCpfSubstring127.54 ns-56%

My solution was 50% faster than the Stack Overflow one!

Final Solution

Even that my solution was an acceptable implementation I felt it could still be improved, the problem is that usingSubstring for extracting the CPF sections generates new allocations in the memory for each part of the string.

To make this process efficiently instead of creating newsubstrings we ideally could just pickslices of the original input and add the required separators. Here is where the power ofSpan andSlice can be used.

TheSpan<T> type provides a way to point to a specific part of an object in the memory by using theSlice method, for manipulating strings this can be very helpful in scenarios where parts of the existing string can be used to produce the desired result.

So, by just applying the extension methodAsSpan into the string and usingSlice I implemented this new solution:

publicstringFormat(stringcpf){varcpfAsSpan=cpf.AsSpan();return$"{cpfAsSpan.Slice(0,3)}.{cpfAsSpan.Slice(3,3)}.{cpfAsSpan.Slice(6,3)}-{cpfAsSpan.Slice(9,2)}";}
Enter fullscreen modeExit fullscreen mode

After running the benchmark again, we have:

MethodMeanRatio
FormatCpfConvert301.97 nsbaseline
FormatCpfSubstring127.54 ns-56%
FormatCpfAsSpan75.94 ns-74%

Final solution is almost 75% faster than the initial one!

Conclusion

I hope this gives you an idea ofSpan type and its benefits regarding performance. Although this type was introduced a few years ago is not common to see it being used or explained.

Also, this experience reinforced practices that I recommend and try to follow every day:

  • Stay up to date about the features of the programming language/framework that you are working with, you never know when you can find something useful to apply in your day-to-day activities
  • Make it work, then make it better/faster
  • Don't blindly rely on solutions from the internet

Links:

Top comments(0)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

.NET Specialist
  • Education
    FATEC
  • Work
    Software Engineer
  • Joined

Trending onDEV CommunityHot

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp