@manhng

Welcome to my blog!

.NET Performance Tips

July 26, 2021 18:08

.NET Performance Tips (edit)

C#.NET Tutorials For Beginners and Professionals - Dot Net Tutorials

.NET Performance Tips (C# Perf Tips)
--------------------------------------------------
+ Always choose the proper storage mechanism to get the best performance.
+ ArrayList<object> is much slower than List<int>
+ Empty destructors should not be used.
+ Use a for loop is much faster than a foreach loop.
+ Use the structure is much faster than the class.
+ Always use Stringbuilder for String concatenation operations.
+ The data member is assigned using a property is much slower than direct assignment.
+ Use the BenchmarkDotNet (Powerful .NET library for benchmarking)
+ Use the Environment.ProcessId is much faster than the Process.GetCurrentProcess().Id

References:

.NET Performance Tips
.NET Performance Tips | Microsoft Docs

5 Tips to Improve Performance of C# Code
5 Tips to Improve Performance of C# Code (c-sharpcorner.com)

Performance Improvements in .NET 5
Performance Improvements in .NET 5 | .NET Blog (microsoft.com)

Update to HttpClient and Automatic Decompression
Update to HttpClient and Automatic Decompression | .NET Blog (microsoft.com)

+ Garbage Collection (GC)
+ Framework Class Library (FCL)
+ Base Class Library (BCL)
+ Just-In-Time (JIT)
+ Ahead Of Time (AOT)
+ IsIReadOnlyCollection
+ Regular Expressions
+ Threading and Async
+ Collections (Span, Record)
+ ConcurrentDictionary is faster than Dictionary
+ ImmutableArray<int>
+ ImmutableList<int>
+ IEnumerable<int>
+ LINQ
+ Networking
+ JSON (System.Text.Json)
+ ReadOnlySpan<byte>
+ ReadOnlySpan<char>
+ ReadOnlySpan<int>
+ Span<T>
+ ThrowArgumentNullException
+ ThrowHelper.ThrowArgumentOutOfRangeException
+ IsIReadOnlyCollection
private List<string> _list = new List<string>();
// IReadOnlyCollection<out T> is covariant
public bool IsIReadOnlyCollection() => IsIReadOnlyCollection(_list);
+ HashSet<T> is very similar to Dictionary<TKey, TValue>
+ Dictionary<TKey, TValue> is very similar to ConcurrentDictionary<TKey, TValue>
+ BitArray
private bool[] _array;
BitArray Create() => new BitArray(_array);
+ TryParseExact and TryAddWithoutValidation
var m = new HttpResponseMessage();
m.Headers.TryAddWithoutValidation("Date", "Sun, 06 Nov 1994 08:49:37 GMT");
return m.Headers.Date;
+ CopyToAsync
+ X509Certificates
+ StringBuilder.Append and StringBuilder.Insert
+ ConcurrentQueue<T>
+ String.OrdinalIgnoreCase
+ Activator.CreateInstance<T>()
+ Utf8Parser.TryParse
+ Task.WhenAny
+ Garbage Collection in .Net Framework
+ String.Split(char separator, StringSplitOptions options = StringSplitOptions.None)
+ System.Text.RegularExpressions (RegexOptions.Multiline, FindFirstChar, IndexOf)
+ Use the ^ and $ anchors
+ Từ khoá volatile chỉ định một biến có thể được thay đổi bởi nhiều tiến trình thực hiện đồng thời.
+ When writing to a field marked volatile, the volatile keyword controls the order in which writes are performed. It does not guarantee that these writes are immediately visible to other threads.
+ The volatile keyword can only be applied to fields of a class or struct. Local variables cannot be declared volatile.
+ Chúng ta sẽ sử dụng volatile khi khai báo biến trong các trường hợp dưới đây:
- Con trỏ trỏ tới địa chỉ của các thanh ghi trong bộ nhớ (Memory - mapped peripheral register)
- Biến toàn cục dùng chung cả trong và ngoài ngắt (ISR Routine)
- Biến toàn cục dùng chung trong nhiều task trong ứng dụng multi-thread
+ Static
Static member là đối tượng trực thuộc 1 class, chứ ko nằm trong 1 thể hiện nhất định nào cả hay nói chính xác hơn nó thuộc class chứ không thuộc instance, và giá trị của nó có thể được dùng ở nhiều thể hiện khác nhau. Nếu 2 thread khác nhau cùng update giá trị của static member thì những đối tượng dùng nó có thể lấy được giá trị cũ chứ không phải giá trị mới nhất.
+ Volatile
Volatile member là 1 đối tượng nằm trên bộ nhớ. Tất cả các thể hiện khác đều có thể thấy được giá trị của nó, sau khi giá trị này được thay đổi kể cả ở thread khác.
+ Volatile là đồng bộ dữ liệu trên 1 đối tượng nhất định giữa các thread, còn synchronized là đồng bộ giá trị của các biến giữa các thread khác nhau.

+ ASP.NET – SameSite Cookie
var c = new HttpCookie("secureCookie", "same origin");
c.SameSite = SameSiteMode.Lax;

+ Choosing Between the Task Parallel Library and the ThreadPool

+ In .NET Framework 4.5: System.IO.Compression
+ In .NET Framework 4.7.2 we have BCL – ZLib decompression support to DeflateStream
+ HttpClient no longer depends on Microsoft.Bcl.Compression
+ Microsoft.Net.Http & System.Net.Http

Choose between .NET Framework & .NET Core
.NET Framework 4.8, .NET Core 3.1, and .NET 5

1) Zip & Unzip (HttpClient.Compression, DotNetZip)
2) TPL and ThreadPool.
3) ADO.NET, Networking, Streams (performance best practices).

Code Reviews
a) Do we really need to implement the thing?
b) Do need to implement all of it?
c) Only write enough code to implement the thing.

Exceptions and Logs One Too Many
Overuse of Thread Synchronization and Locking
The Dreadful Application Hangs
IIS Server Bottlenecks
Frequent Garbage Collection Pauses
Slow Database Calls
An Introduction to Fuzzy String Matching (.NET Performance Optimization: Everything You Need To Know – Stackify)

Common Performance Problems
Here is a short list of a few common application performance problems I’ve encountered in the past:

Unnecessary collection enumeration and allocation (.ToList())
Any kind of string manipulation in loops
Using string.Substring() instead of Span
Using string.Format (or C# 6 interpolation) instead of string.Concat for small operations
Not using async for I/O operations that can be executed in parallel
Wrapping synchronous operations in async wrappers and executing them synchronously
Using List instead of Dictionary for key/id-based access
Unnecessary boxing (var i = 0; object a = i; var j = (int)a;)
Large lock blocks or locking types. Use locks on static instance variables as close as possible to the synchronous operation. Consider the use of ThreadStatic or LocalAsync.
Finding the value in the HashSet<T> takes almost no time compared to finding the value in the List<T> collection.

Categories

Recent posts