code4it-dev / blog-comments

https://www.code4it.dev/
1 stars 0 forks source link

blog/top-6-string-performance-tips/ #63

Open utterances-bot opened 9 months ago

utterances-bot commented 9 months ago

Top 6 Performance Tips when dealing with strings in C# 12 and .NET 8 | Code4IT

Code4IT - a blog for dotnet developers

https://www.code4it.dev/blog/top-6-string-performance-tips/

jamescurran commented 9 months ago

I was going to suggest including s[0] == 'H'; and s[^1] =='o' in your StartsWith/EndsWith testing. But that I realized your input string may be null, which gives us an interesting effect. s?.StartsWith() returns a bool? and can be true/false/null. But s?[0] =='H' returns a raw bool, but goes about it by making a char? from s?[0] before doing the comparison. So, I think we need to those varients, plus also (s != null && s.StartsWith('H')) and (s != null && s[0]=='H') to really find the most performat style.

Also, when considering IsNullOrEmpty vs IsNullOrWhitespace , you also have to look into what you are doing with the string AFTER it passes the test. You are probably going to want to trim it, so you might as well do that first. And

var trimmed = s?.Trim();
if (string.IsNullOrEmpty(trimmed))
{  // use trimmed   }

is probably going to beat

if (string.IsNullOrWhitespace(s))
{
    var trimmed = s?.Trim();
  // use trimmed   
}
bellons91 commented 9 months ago

Yes, that all makes sense! My suggestion is to create the benchmark for your cases and share them here in the comments section :)

jamescurran commented 9 months ago

Is the bench test source code available on github?

bellons91 commented 9 months ago

No, but I shared the whole code in the article. Il mercoledì 3 gennaio 2024 alle ore 14:15:54 CET, James Curran @.***> ha scritto:

Is the bench test source code available on github?

— Reply to this email directly, view it on GitHub, or unsubscribe. You are receiving this because you commented.Message ID: @.***>