Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Some Optimization and Performance Tricks in .Net

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 185
    Comment on it

    Hi Friends. My "Hello World" blog in MVC is taking some time ,so I thought that I should share some performance tips here. Some of them are followed by code and explanations and I believe that you'll find them useful.

    Static Methods are Faster than Instance Methods
           The reason is -you don't need any instance reference resolutions before calling of a static method but for an instance method that resolution is must.

    Try Using Expressions in Arithmetical Functions
           If your method uses multiple arithmetical expressions,use expressions. An example here will clarify the things:-

    using System;
    using System.Diagnostics;
    
    class Program
    {
        static int _temp1 = 5;
        static int _temp2 = 10;
    
        static int Method1()
        {
        // Use local variables to perform computation.
        int a = _temp1;
        int b = a * 10;
        int c = b * _temp2;
        int d = c + 5;
        int e = d - _temp2;
        return e * 2;
        }
    
        static int Method2()
        {
        // Use expression to perform computation.
        return ((_temp1 * 10 * _temp2) + 5 - _temp2) * 2;
        }
    
        const int _max = 300000000;
        static void Main()
        {
        // Test.
        Console.WriteLine(Method1());
        Console.WriteLine(Method2());
        // Clean up environment.
        GC.Collect();
        System.Threading.Thread.Sleep(10);
    
        for (int a = 0; a < 10; a++)
        {
            var s1 = Stopwatch.StartNew();
            for (int i = 0; i < _max; i++)
            {
            Method1();
            }
            s1.Stop();
            var s2 = Stopwatch.StartNew();
            for (int i = 0; i < _max; i++)
            {
            Method2();
            }
            s2.Stop();
            Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000 * 1000) /
            _max).ToString("0.00") + " ns");
            Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000 * 1000) /
            _max).ToString("0.00") + " ns");
        }
        Console.Read();
        }
    }
    

    If you are worried about "Stopwatch" , it's a class that provides a set of methods and properties for measurement of elapsed time and available under System.Diagnostics namespace.

    So run the above program and you'll find the difference between Method1 and Method2. Method 1 always takes more time because of more variables used and more assignments done.

    Assigning a Global Field to a Local one inside a Method Improves Performance
           We should assign the data of any global field to a local one and then continue the operation inside any method. Didn't get it? Nothing to worry about. Let's take a look at code

    using System;
    using System.Diagnostics;
    
    class Program
    {
        static int _temp1; // Static field
    
        static void Method1()
        {
        // Increment the static field ten times.
        for (int i = 0; i < 10; i++)
        {
            _temp1++;
        }
        }
    
        static void Method2()
        {
        // Load static field into variable.
        // ... Increment that ten times, then copy the value.
        int copy = _temp1;
        for (int i = 0; i < 10; i++)
        {
            copy++;
        }
        _temp1 = copy;
        }
    
        // === Start benchmark code
        const int _max = 1000000;
        static void Main()
        {
        var s1 = Stopwatch.StartNew();
        for (int i = 0; i < _max; i++)
        {
            Method1();
        }
        s1.Stop();
        var s2 = Stopwatch.StartNew();
        for (int i = 0; i < _max; i++)
        {
            Method2();
        }
        s2.Stop();
        Console.WriteLine(((double)(s1.Elapsed.TotalMilliseconds * 1000 * 1000)
            / _max).ToString("0.00 ns"));
        Console.WriteLine(((double)(s2.Elapsed.TotalMilliseconds * 1000 * 1000)
            / _max).ToString("0.00 ns"));
        Console.Read();
        }
    }
    

    When you run the code you see the difference. That difference is significant. But why is that difference coming at first place? The reason is the global fields are created in Heap and local fields are called in registers. So registers are always faster than Heap which is an unmanaged memory and searching in a Heap is always slower. So we find two points here.
    1-The point described in detail just above
    2-More line of code is not always that bad(logic behind memory management matters,not line of codes)

    Switch is Faster than if-else
            If a switch contains more than five items, it's implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of ifs where the last item takes much more time to reach as it has to evaluate every previous condition first.

    StringBuilder is Faster than String Object if String Modification is Required
            Appending string with a string builder is always faster than appending in string object as string object is immutable i .e.it can not be changed once defined. So if we append something in string object,it removes and recreates the whole string which is resource consuming.

    Using Byte Array whenever possible
            If we need to store int values for some purpose and the range is limited(not that of int or long) we should use byte array for the purpose. It saves memory.

    Array vs ArrayList
            I won't say that arraylist is bad or array is good. Both of them have their uses . So points for both are written below and you can get them as pros or cons as per your choice:-
    Array:-
    1-Homogeneous collection of data
    2-Size should be defined in prior
    3-Search by indexes,so it is faster
    4-Is strongly typed

    ArrayList:-
    1-Heterogeneous Collection of data
    2-No fixed size
    3-Search is slower because it will need a cast to get back to your original type(Heterogeneous collection)
    4-Not strongly typed

    Use for loop instead of foreach whenever possible
           Try using for loop if it can be used in your scenario as it is faster than foreach. How?:-
    1-Foreach uses two variables at least in it's loop construct which take memory but for loop uses one variable. 2-Forloop traverses through indices but foreach loop traverses with data value in it's variable which is slower.

    Avoiding Unnecessary Array Sorts
            If you are having any array in the code,you shouldn't sort it unless required. Because sorting any data structure is a huge overhead on system. So try not to use sorting whenever you like,use it whenever required.

    Removing Unused Assembly References
            It's a good practice to remove the unused assembly references from your application. For that you need to right click on the your .cs file and under option "Organise Usings" click "Remove Unorganized Usings".

    Some Final Words:-
           The performance tuning in any application is not a concrete thing to discuss and list of the tasks for optimizations is endless. It's kind of an endless debate because in the thing you find bad in one scenario,might prove better in another. So no application can be 100% optimized but it can be optimized as per requirements.

    This articles tells some points about optimization for performance but they are not hard and fast rules for optimization.

    For example we can take scenario of for and foreach loop. I just said that for loop is better,but the tasks which foreach executes(iterating through collections) with ease,is cumbersome with for loop. And it's possible that by maintaining variables in for loop ,we eliminate that performance difference between the two and get the same result for both. Then all overhead taken by us will be of no use.

    Optimization for performance is like using a very sharp edged knife. Use it wisely and you'll craft an ultimate application. Overuse it and you'll lose the desired performance. It depends upon how we use it.

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: