Performance Code in C#: Part 1
In this competitive world to met business requirements in the timeline, we skip our code optimization and it causes the low performance of the application. In many cases, either we get a well-optimized scalable code or the code that will just do the business needs.
The Performance Code in C#: Part 1 article is all about how to check the performance of the code and some code optimizes way but in the coming parts of the article, we are going to check what are best ways to optimize/improve/standardized the code.
When we are talking about coding performance, there are 3 major factors we need to consider.
- When to measure the performance of the code. ?
- What to measure in the code in regards to the performance. ?
- How to measure the performance of the code. ?
When to measure the performance of the code. ?
- Literally every time. (Before we ask our colleague to review the code we need to analyze the performance of the code)
- Even with very small development.
What to measure in the code in regards to the performance. ?
- CPU %
- Memory Allocation
- Garbage Collection factor
- Which method/code line takes how much time.
How to measure the performance of the code. ?
- There are inbuilt tools in the visual studio to do the same.
- PerfTips
- Performance Profiler
- Diagnostic Tools
- BenchmarkDotNet (NuGet package)
PerfTips
- It is an integrated tool that helps us to monitor and analyze the performance of our code while we are debugging.
- When the debugger stops execution at a breakpoint or stepping operation, the elapsed time between the break and the previous breakpoint appears as a tip in the editor window.
- Source Code Github link: https://github.com/NileshYendhe/PerformanceCodeInCSharp/tree/master/perftips
- As you can see elapsed time of the code execution in the below-mentioned screenshot.
Performance Profiler
- It is an integrated tool that helps us to monitor and analyze the performance of our code.
- You can open the performance profiler window by following the menu. Select Debug and then Performance Profiler.
- Tools available in the Performance Profiler :
- CPU Usage: The CPU Usage performance tool shows the CPU time and percentage spent executing code. (https://docs.microsoft.com/en-us/visualstudio/profiling/cpu-usage?view=vs-2019)
- .NET object allocation: Where objects are being allocated. (https://docs.microsoft.com/en-us/visualstudio/profiling/dotnet-alloc-tool?view=vs-2019)
- Memory Usage: We can take snapshots of the code, how much memory has been used. (https://docs.microsoft.com/en-us/visualstudio/profiling/memory-usage-without-debugging2?view=vs-2019)
- .NET Async Tool: Asynchronous events are organized into activities chronologically. Each displays its start time, end time, and duration. (https://docs.microsoft.com/en-us/visualstudio/profiling/analyze-async?view=vs-2019)
- Database Tool: Use the Database tool to record the database queries (https://docs.microsoft.com/en-us/visualstudio/profiling/analyze-database?view=vs-2019)
- We have taken an example of Class and Struct to check the performance.
- If you check the below-mentioned code, we are just adding values to the class and struct. But the performance of the struct over class is way faster.
- Source Code Github link: https://github.com/NileshYendhe/PerformanceCodeInCSharp/tree/master/performanceprofiler
- As you can see in the below-mentioned screenshot we have analyzed the CPU usage of our code.
- Struct is taking very little time compared to the class. We have also bifurcated which line is taking more time in both the methods.
- As we can see in the below-mentioned screenshot, the initialization of the class is taking more time as compared to the other code lines.
- As we can see in the below-mentioned screenshot, the initialization of the struct is taking little time compared to the initialization of the class.
Diagnostic Tools
- It has the ability to monitor performance while debugging and correlate performance data with debugging activity.
- You can open the Diagnostic Tools window by following the menu. Select Debug then Windows and then Show Diagnostic Tools.
- We can capture Events, Memory Usage, and CPU Usage using this tool.
- Source Code Github link: https://github.com/NileshYendhe/PerformanceCodeInCSharp/tree/master/diagnostictools
- To check how diagnostic tools works, we have used the same example which we have mentioned above of class and struct.
- As you can see in the below-mentioned screenshot we have captured the Memory Usage, what memory has been allocated at the starting of the application and at the end of the application.
- As you can see in the below-mentioned screenshot we have captured the CPU percentage per method.
Benchmark DotNet
- It is a very useful NuGet package where we can actually do the kind of load test of the code.
- BenchmarkDotNet helps you to transform methods into benchmarks, track their performance, and share reproducible measurement experiments.
- More Info: https://github.com/dotnet/BenchmarkDotNet
- We have done some analysis of the code/functionality which we are using in our day to day basis work.
- Source Code Github link: https://github.com/NileshYendhe/PerformanceCodeInCSharp/tree/master/benchmarkdotnet
Comparisons
String Concatenation
- To check which method performs well in concatenating the string we have used Interpolation, PlusOperator, StringConcatMethod, StringJoinMethod, StringFormat, and StringBuilder.
- And after doing the benchmark, it clearly states that StringBuilder is performing well while doing the concatenation of the strings.
- If you check the below-mentioned code how it works.
- Please check the below-mentioned screenshot. As per the Rank column, StringBuilder comes first.
Dynamic type
- Many people declare variables using dynamic type. But sometimes it causes the performance of the application.
- When we did the benchmark of the application using dynamic type and JObject type. JObject type is the winner.
- If you check the below-mentioned code how it works.
- Please check the below-mentioned screenshot.
JSON
- NewtonSoft is a very vast and powerful NuGet package.
- But sometimes, if our use case is simple and gets fulfilled by Microsoft’s default JSON serializer System.Text.Json.JsonSerializer.Serialize, we should avoid using NewtonSoft library.
- When we did a benchmark of two of the methods, NewtonSoft and System.Text.Json.JsonSerializer.Serialize, System.Text.Json.JsonSerializer.Serialize is performing well.
- If you check the below-mentioned code, how it works.
- Please check the below-mentioned screenshot.
FileRead
- We get requirements (development) every other day to read the file and accomplish the task.
- To check which method performs better in reading the file, we have used methods like ReadLine, ReadLines, ReadAllText, ReadAllBytes, ReadAllLines, and ReadAllLinesAsync.
- If you check the below-mentioned code, how it works.
- And after did the benchmark of those methods a very simple ReadLine method performs very well.
Note: All of the above test cases, use cases as per scenarios. Before applying any solution, check your use case and run the above-mentioned tools/methodologies and then choose the best way which will benefit you.
Other Tools
PerfView
- PerfView is a free performance-analysis tool that helps isolate CPU and memory-related performance issues. It is a Windows tool.
- https://www.microsoft.com/en-us/download/details.aspx?id=28567
PerfMon
- Performance Monitor is a system monitoring program,
- It monitors various activities on a computer such as CPU or memory usage.
- https://docs.microsoft.com/en-us/sysinternals/downloads/procmon
MiniProfiler
- Designed by StackOverflow, it does not attach to every single method call, but it checks SQL, ADO.NET, LINQ-to-SQL calls. (We can say tiny version of the NewRelic)
- https://miniprofiler.com/
Netling
- Netling is a load tester client for easy web testing. It is extremely fast while using little CPU or memory.
- https://github.com/hallatore/Netling
Github link
If you have any suggestions apart from these, feel free to leave a response.
I hope this helps some people understand a little more about how to check the Performance of the Code in C#
Thank you so much… !!!
Enjoy coding…