C# performance and memory optimization ๐ก
For a very long time, I used to compare strings in my codebase by doing stringA.ToLower() == stringB.ToLower(). I did not know that I was consuming a lot of memory. A thread ๐งตโฌ๏ธ #csharp#dotnet
Even if computers are very powerful nowadays, it's recommended to build memory-efficient systems because low memory allocation increases performance of the system. So it's always a good idea to use less memory when possible.
Recently, I've tried to measure two ways of comparing strings:
1โฃ My old way of doing (see the first tweet of the thread)
2โฃ the use of string[.]Compare method.
To do so, I've created quite a huge list of alphabet letters (1024 items of each letter) and two methods that will count how many occurrences of a given letter we have in the list.
As we can see, the first method is comparing the letters by testing their lowercase values equality, and the another by using the string[.]Compare method. Here is the memory allocation results :
The memory allocated by the WithoutCompare method is HUGE ๐ฏ๐ฎ๐ฑ
Also, the Garbage Collector (the "Gen" parameter) has a lot more work to perform with the first method. The difference is very significant. But why such a difference?
It's quite normal though : in C#, strings are immutable. So every time the ToLower method is called on a string, a brand new string is created to hold the lowercase value. As a result, a piece of memory is allocated for it. That is why the first method is so memory-consuming.
On a contrary, the String[.]Compare method does not create a new string. So memory is not wasted here.
In conclusion, when you need to make string comparison on an important amount of data, use the string .Compare method. It will help you avoid some performance issues and memory leaks. You can learn more about the string[.]Compare method here : docs.microsoft.com/en-us/dotnet/aโฆ) ๐๐
I hope you liked this thread. Fore more tips about C# and .NET, do not hesitate to give a follow! ๐ #dotnetlovesme
๐
Thread reopened ๐
As you guys are asking in the replies, let's add some more information here.
As the string comparison with the ToLower() method is excluded (memory-inefficient), let's focus on the two remaining methods: the string .Compare() and the string.Equals()
I've compared the two methods with the Ordinal IgnoreCase comparison mode this time (read the comments if you want to know why)
And here are the results. The allocated memory is quite the same, but The Equals() method seems to be faster ๐.
โข โข โข
Missing some Tweet in this thread? You can try to
force a refresh