Showing posts with label C#. Show all posts
Showing posts with label C#. Show all posts

Sunday, November 9, 2025

Dotnet Core - Performance Tuning of Applications

 🚀 How to Improve Performance in ASP.NET Core Applications

Performance optimization in .NET Core is multi-layered, covering areas from code-level tuning to infrastructure scaling.
Here’s a structured breakdown:





🧱 1. Use Built-in Caching

🔹 Memory Cache (for small-scale, single-server)

builder.Services.AddMemoryCache(); public class ProductService { private readonly IMemoryCache _cache; public ProductService(IMemoryCache cache) => _cache = cache; public Product GetProduct(int id) { return _cache.GetOrCreate($"product_{id}", entry => { entry.SlidingExpiration = TimeSpan.FromMinutes(5); return LoadProductFromDb(id); }); } }

🔹 Distributed Cache (for load-balanced apps)

Use Redis, SQL Server, or AWS ElastiCache.

builder.Services.AddStackExchangeRedisCache(options => { options.Configuration = "localhost:6379"; });

✅ Benefit: Reduces DB hits and speeds up responses.


⚙️ 2. Enable Response Caching

Cache HTTP responses for static or infrequently changing data.

builder.Services.AddResponseCaching(); app.UseResponseCaching();
[ResponseCache(Duration = 60)] public IActionResult GetWeather() => Ok("Sunny");

✅ Benefit: Reuses responses instead of regenerating data.


⚡ 3. Use Asynchronous Code

ASP.NET Core is non-blocking. Always use async/await for I/O operations:

public async Task<IActionResult> GetProductsAsync() => Ok(await _db.Products.ToListAsync());

✅ Benefit: Frees up threads → handles more concurrent requests.


🧰 4. Optimize Entity Framework Core

  • Use AsNoTracking() for read-only queries.
  • Fetch only needed columns via Select().
  • Use compiled queries for hot paths.
  • Use connection pooling.

Example:

var products = await _context.Products .AsNoTracking() .Select(p => new { p.Id, p.Name }) .ToListAsync();

✅ Benefit: Reduces EF overhead and memory allocations.


🧩 5. Compression & Minification

Enable Response Compression middleware:

builder.Services.AddResponseCompression(); app.UseResponseCompression();

Compresses JSON, HTML, CSS, etc., reducing network load.


💾 6. Use Data Transfer Optimization

  • Use DTOs to avoid over fetching large models.
  • Paginate results.
  • Use gzip/brotli compression and HTTP/2.

🌐 7. Use CDN & Static File Optimization

Host static assets (JS, CSS, images) on a CDN like CloudFront.
Also, use cache headers:

app.UseStaticFiles(new StaticFileOptions { OnPrepareResponse = ctx => { ctx.Context.Response.Headers.Append("Cache-Control", "public,max-age=604800"); } });

🧮 8. Connection & Pooling

Use IHttpClientFactory for efficient, pooled HTTP calls:

builder.Services.AddHttpClient("MyClient");

Avoids socket exhaustion caused by frequent new HttpClient instances.


🧠 9. Reduce Middleware Overhead

Register only necessary middleware, and put frequently used ones first (e.g., authentication before routing).


🧩 10. Use Output Caching (ASP.NET Core 7+)

Output caching stores full HTTP responses:

builder.Services.AddOutputCache(); app.UseOutputCache();
[OutputCache(Duration = 60)] public IActionResult GetProducts() => Ok(Products);

✅ Much faster than recomputing each request.


☁️ 11. Use Cloud & Deployment Optimization (AWS Context)

On AWS, you can:

  • Use Elastic Beanstalk or ECS/EKS for autoscaling.
  • Add AWS ElastiCache for distributed caching.
  • Use AWS CloudFront CDN.
  • Add Application Load Balancer for traffic balancing.
  • Store assets in S3 instead of app server.

✅ You can also enable AOT (Ahead-of-Time Compilation) for startup performance improvements.


🧪 12. Profiling & Diagnostics

Use tools like:

  • dotnet-trace, dotnet-counters
  • Application Insights
  • MiniProfiler
  • AWS X-Ray (for distributed tracing)

✅ Identify slow methods, DB queries, or excessive GC pressure.


🧠 13. Memory Management

  • Use Span<T>, Memory<T> for high-performance code.
  • Avoid large object allocations.
  • Prefer pooled objects (ArrayPool<T>).
  • Release disposable resources properly.

✅ Summary Table

AreaTechniqueBenefit
CachingMemory, Redis, Output CacheReduce recomputation
Async I/Oasync/awaitHandle more requests
EF CoreAsNoTracking, ProjectionOptimize DB performance
CompressionGzip, BrotliReduce payload
MiddlewareOptimize pipelineReduce latency
CDN/StaticCache headersReduce load
DiagnosticsProfilers, LogsIdentify bottlenecks

💡Summary (Short Answer)

"In ASP.NET Core, I improve performance using multi-level caching (in-memory, distributed, and output), async programming, optimized EF Core queries, response compression, and CDN-based static content delivery. I also use IHttpClientFactory for efficient HTTP calls, limit middleware overhead, and profile apps with Application Insights or AWS X-Ray to find hot spots. In cloud deployments, I leverage autoscaling and caching via AWS ElastiCache and CloudFront."

Friday, July 1, 2016

Virtual Vs Abstract

Differences between Abstract & Virtual functions -

Members
  • Abstract function doesn't contain any body but a virtual function contain body 
  • We must be implement the abstract function in derived class but it is not necessary for virtual function 
  • Abstract function can only use in abstract class but it is not necessary for virtual function 
  • Abstract function are called pure virtual function
  • It must be a function member. That is, fields and constants cannot be abstract members.

    Class
    • You cannot create instances of an abstract class.
    • An abstract class is declared using the abstract modifier
    • An abstract class can contain abstract members or regular, nonabstract members.
    • An abstract class can itself be derived from another abstract class
    • Any class derived from an abstract class must implement all the abstract members of the class by using the override keyword, unless the derived class is itself abstract.

    abstract class Helloworld
    {
        public int Int1 { get; set; } //Non Abstract property

        public abstract int Int2  //Abstract Property
        {
            get;
            set;
        }

        public  Helloworld()  //Constructor
        {
            Console.WriteLine("Helloworld Constructor");
        }

        public void Method1()   //Non Abstract Method
        {
            Console.WriteLine("Helloworld Method1");
        }

        public abstract void Method2();  //Abstract Method

         ~Helloworld()  //Destructor
        {
            Console.WriteLine("Helloworld Destructor");
        }
    }

    class Drived : Helloworld
    {
        public int Val;
        public override int Int2
        {
            get
            {
                return Val;
            }
            set
            {
                Val=value;
            }
        }

        public override void Method2()
        {
            Console.WriteLine("Drived Method2");
        }
    }
    class Program
    {
        static unsafe void Main(string[] args)
        {

            Drived Dr = new Drived();
            Dr.Int1 = 10;
            Dr.Int2 = 20;
            Dr.Method1();
            Dr.Method2();
            Console.ReadLine();
        }
    }

    Monday, November 9, 2015

    Extension Methods

    Extension method enables to add new method(s) into a class (type / library) without modifying, recompiling or creating derived type.

    Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type.

    Scenario :
    We've a class library 'Calculations' in which we have class 'Airithmatics' that contains method 'Add'.
    Now we want to add 2 more methods 'Subtract' & 'Multiply' in this library without updating this library.

    Limitation: Any extension method(s) with same signature to method(s) of main library / type will never be called

    Steps to implement:
    1. Create new library named 'ArithmaticAddons'
    2. Add reference of main library 'Calculations'
    3. Create a static class 'ArthAddons' in new library
    4. Add new methods to this class as static method, you want to create as extension methods. Pass main library 'Airithmatics' in methods
    5. Add reference of both the libraries 'Calculations', 'ArithmaticAddons' in client code
    6. Create object of main library 'Airithmatics'
    7. With the object of main library 'Airithmatics', you can see methods of main library & extension methods
    8. Extension methods displays with a down arrow




















    Custom Library Code:
    using  Calculations;  //Main library contains ‘Add’ function

    namespace ArithmaticAddons
    {
        public static class ArthAddons
        {
            public static int Subtract(this Airithmatics obj, int num1, int num2)
            {
                return num1 - num2;
            }
     public static int Multiply(this Airithmatics obj, int num1, int num2)
            {
                return num1 * num2;
            }
        }

    }

    Client Code:
    using Calculations; //Main library contains ‘Add’ function
    using ArithmaticAddons; //Custom library contains subtract & Multiply extension methods
    namespace ExtensionMethods
    {
      class Program
      {
        static void Main(string[] args)
        {
          Airithmatics obj = new Airithmatics();
          Console.WriteLine(obj.Add(20, 215).ToString());
          Console.ReadLine();

          //Extension method Subtract & Multiply call
          Console.WriteLine(obj.Subtract(220, 215).ToString());
          Console.WriteLine(obj.Multiply(2, 20).ToString());
          Console.ReadLine();
        }
      }
    }

    Wednesday, November 4, 2015

    Anonymous Methods

    A Anonymous method is a code block assigned to some delegate.
    This concept is introduced in .Net Framework 2.0, before it only named methods could be used with delegates

    Scenarios to use:
    1. When want to use delegate in same method
    2. When code is small
    3. Performance wise anonymous methods are faster than named method

        class Program
        {
            delegate void delAnonymousMethods(int i, int j);
            static void Main(string[] args)
            {
                //anonymous method
                delAnonymousMethods delAM = delegate(int i, int j)
                {
                    Console.WriteLine((i + j).ToString());
                };

                delAM(10, 20);
                Console.ReadLine();
            }
        }


    Some examples of Anonymous functions


    delegate (int x) { return x + 1; }      // Anonymous method expression
    delegate { return 1 + 1; }              // Parameter list omitted
    x => x + 1                              // Implicitly typed, expression body
    x => { return x + 1; }                  // Implicitly typed, statement body
    (int x) => x + 1                        // Explicitly typed, expression body
    (int x) => { return x + 1; }            // Explicitly typed, statement body
    (x, y) => x * y                         // Multiple parameters
    () => Console.WriteLine()               // No parameters
    async (t1,t2) => await t1 + await t2    // Async



    Asynchronous Method Calls using Delegate

    Asynchronous method call means main execution goes continue and method executed parallel, when method execution gets completed it notifies back to main execution program / caller (client).

    Example
    namespace AsyncCallBack
    {
        class Program
        {
            public delegate string delTask();
            public static string results;
            static void Main(string[] args)
            {
                clsBigTask objclsTask = new clsBigTask();
                delTask del = objclsTask.BigTask;
              
                AsyncCallback asyncCall = new AsyncCallback(CallBackMethod);
                del.BeginInvoke(asyncCall, del);
              
                Console.WriteLine("Main task completed @" + DateTime.Now.ToString());
                Console.ReadLine();
            }

            public static void CallBackMethod(IAsyncResult result)
            {
                delTask mydel = (delTask)result.AsyncState;
                results = mydel.EndInvoke(result);
                Console.WriteLine(results);
            }
        }

        public class clsBigTask
        {
            public string BigTask()
            {
                Thread.Sleep(6000);
                return "Big Task completed";
            }
        }
    }

    Output

    Sunday, October 25, 2015

    out Vs ref

    Both are used to pass variable(s) as a reference from one function to another function.
    out: It does not carry existing value of variable and ask to initialize it in function 2, but returns the new out put value. so its one way communication.

    ref: It carries existing value of variable in function 1, and after operations on existing value returns the out put value, so its two way communication.

        static void Method(out int i, ref int j)
        {
            i = 50; //initialization required for out but not for ref

      i = i + 10;
      j = j + 10;
     
        }
        static void Main()
        {
            int value1 = 20, value2 = 20;
            Method(out value1, ref value2);
            // value1 is now 60
            // value2 is now 30

        }

    Saturday, October 24, 2015

    Delegate in .Net

    A delegate is a type that defines a method signature. When you create an instance of the delegate, you can associate a method to the instance of compatible signature, now you can call or invoke that method by the delegate instance.
    1. Delegates are used to pass a method as argument to other method. 
    2. A delegate instance can be assigned a method of any accessible class or struct that matches signature of delegate, method can be static or instance method.
    3. Delegate types are sealed they can not be derived from. (Sealed restricts inheritance of any class, like struct can't be inherited as they are sealed)
    4. Instance of delegate is an object so it can be assign to a property or can be pass to a method as parameter.
    5. Delegate can be multicast.
    Using delegate is 4 step process 
    1. Declare delegate 
    2. Create instance / object of delegate (Create delegate pointer)
    3. Reference delegate instance to one or more methods with same signature
    4. Call delegate 

    Example
    namespace ClassLibrary1
    {
        public class Class1
        {
            //-1-Declare delegate
            public delegate string DelSaveData(string msg);

            public DelSaveData SaveClientData()
            {
                //-2-Create delegate pointer (object)
                DelSaveData delObj = null;
               
                //-3-Point method(s) / reference to method(s)
                delObj += SaveData;
                delObj += SendMailtoClient;
                delObj += SendSMStoClient;

                return delObj;           
            }
           
            private string SaveData(string msg)
            {
                return "Data saved at : " + DateTime.Now.ToString();
            }
            private string SendMailtoClient(string msg)
            {
                return "Email sent to client at : " + DateTime.Now.ToString();
            }
            private string SendSMStoClient(string msg)
            {
                return "SMS sent to "+ msg +" at : " + DateTime.Now.ToString();
            }

        }
    }

    Client Code
    private void button1_Click(object sender, EventArgs e)
    {
       Class1 objclass1 = new Class1();
       Class1.DelSaveData objDelSaveData = objclass1.SaveClientData();
               
       //-4-Execute/call the delegate
       string s = objDelSaveData.Invoke("Client1");
    }

    Point to be noted in delegate multi casting : 
    1. Passed parameter(s) is available inside all assigned methods. Here "Client1" will be available to all three assigned method in msg variable.
    2. Delegate returns output returned by last called method. Here delegate invoke will return output returned by SendSMStoClient.
    string s = objDelSaveData.Invoke("Client1");

    CI/CD - Safe DB Changes/Migrations

    Safe DB Migrations means updating your database schema without breaking the running application and without downtime . In real systems (A...