AspNet 6 Performance (C-Sharp 9 Enhancements)

C# Best Practices

[NB]: The kind of datastructure you use in the application matters when it comes to performance.
           Load the data from Database into a Datastructure and all Operations e.g. UI ajax queries should query from the Datastructure /lookups.

1. Aways Sort your lists so that the BranchPredictor ina CPU Core can predict when a for-loop and prefetch data from an L1, L2 and L3 (worst case fetch data from Memory Stick which takes couple nano seconds).

2. Look in C# Class Distructors, basically it reverses the Constructor Setters and get Properties. e.g.

var (h,t, k,c) = myNiceClassConstructor();

3. How to Deallocate Object in a Class after Use
    - Use Structs (Value based references "me" and "Me" are not equall)
    - Use Spans
    - Use Array Pooling
    - Never Load Data in memory you don't need, (The CPU fetches data it does not need from memory then dumps it, gabarge)
       If the CPU has a small Cache-Line, it is forced to go roundtripe to Memory to get the Data (that it doens not even need).

4. CPU Operations
    - Prefetcher fetches data from Memory and Populates

5. Shorter tables Column are faster than longer Table Columns this is because a Developer can restrick how many rows to retrieve by using a where clause.
6. Performance "How to deallocate Objects in Memory" or atleast free memory up after usage
   - Make use of IDisposabled and dispose objects in that class after usage
     - (My Own theory): Call GC to clean up regularly so objects allocated on the Stack can be collected and free up memory.
     - Use a "Using Statement" to implement IO operations, this frees up objects allocated on the Stack as well as the Heap after usage.
     - Use WeakReferences<MyClassObject> to work with Data Modals, this lets the GC know to collect that Object Allocation in memory after it has been used.
     e.g. Dictionary<int, WeakReference<MyDataModalClass>> _myDictionary = new();
     - [NB] You can allocate Memory in C# by using : private intPtr _head = Marshale.AllocGlobal(4);


 Tools to help Look into Memory Usage of an Application

   - Use DotPeek (app developed by JetBrain) to peak into Memery Usage
   -  Use Windows Built-In "Performance Monitor" to monitor Gen1, Gen2 and Gen3 Object Allocation in Memory


[Note] References
- If you are passionate about the Speed of your code, it is important that you consider, Cache/Memory
   heirarchy as you design and implement your algorithms and datastructure
    - Jan Gray

-  Cache-Line are Key!! undoubtly if you will make even single errors in data layout, you will get 100 x slower solutions! No Joke.
      - Dimtriy Vyukov






Edit this Article
If you log in, you will be notified when someone leaves a comment.

Other users would like to know if this solution helped you.


© 2022 - ErnesTech - Privacy