November 14, 2011

Algorithm

  What is algorithm?

         A method that can be used by a computer for the
         solution of a problem.

         A sequence of computational steps that transform
         the input into the output.

 Basic Data Structures

Search Trees and Skip Lists

Sorting, Sets, and Selection

Fundamental Techniques

Text Processing

Number Theory and Cryptography

November 9, 2011

What is Open Source?

open source refers to a program in which the source code is available to the general public for use and/or modification from its original design free of charge, i.e., open
Open source code is typically created as a collaborative effort in which programmers improve upon the code and share the changes within the community.

Customer Relationship Management
Sugar CRM,Splendid CRM
Target
Contact
Lead---more known to you
User----customer,staff
List
Campaign---email,phone,web
Account---can be company or customer

A library is a collection of functions / objects that serves one particular purpose. you could use a library in a variety of projects.

An API (application programming interface) is a definition ('interface') of how to work with another application, system or technology. It essentially defines the operations that are available to interact with that other system. An API can be a library (meaning that the API is wrapped in a library or set of classes), but the distinction is that an API always references an external system - whether it's a database, web service, another application, or the operating system itself.
A Framework is a larger concept - it will normally contain a number of libraries and APIs to perform common tasks. It exists on a higher conceptual level - it's not just a collection of tools, but also a collection of design patterns, best practices, and methodologies. A software Framework is an extension of a a general framework - its meanings include being a foundation from which things are built, providing support and structure, and giving guidance and definition to requirements.

October 27, 2011

Delegate :Calling Method indirectly via pointer

It is like Function Pointer.
It point to the method or function at runtime.

Declared Delegate and Method should have same number of argument and return type


Callback


September 14, 2011

Improve ASP.net Application Performance


Coding level
Hardware level
Connectivity & bandwidth

Disable Session State
Disable Session State if you’re not going to use it.  By default it’s on. You can actually turn this off for specific pages, instead of for every page: EnableSessionState="false"

Output Buffering
Take advantage of this great feature.  Basically batch all of your work on the server, and then run a Response.Flush method to output the data.  This avoids chatty back and forth with the server.
<%response.buffer=true%>
Then use: <%response.flush=true%>  


Avoid Server-Side Validation

Repeater Control Good, Data List, Data Grid, and Data View controls Bad
Deploy with Release Build

Make sure you use Release Build mode and not Debug Build when you deploy your site to production. If you think this doesn’t matter, think again.  By running in debug mode, you are creating PDB’s and cranking up the timeout.  Deploy Release mode and you will see the speed improvements.

Turn off Tracing
Tracing is awesome, however have you remembered to turn it off? If not, make sure you edit your web.config
<Configuration>
<system.web>
<trace enabled="false" pageOutput="false" />
<trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true"/>
<compilation debug="false" />
</system. Web>
</configuration>

Use Page.IsPostBack
Use StringBuilder
Turn Off ViewState
If you are not using form postback, turn off viewsate, by default, controls will turn on viewsate and slow your site.

Use the AppOffline.htm
Use Paging
Take advantage of paging’s simplicity in .net. Only show small subsets of data at a time, allowing the page to load faster.  Just be careful when you mix in caching. 

Use the Finally Method
Use threading
Trim your page size ( reduce the size of your pages)
Enable buffering.
Partition page content to improve caching efficiency and reduce rendering.
Ensure pages are batch compiled.
Ensure debug is set to false.
Optimize expensive loops.
Consider using Server.Transfer instead of Response.Redirect.
Use client-side validation.
Use For instead of ForEach in performance-critical code paths.

In case you use the session state only to retrieve data from it and not to update it, make the session state read only by using the directive:
<@%Page EnableSessionState ="ReadOnly"%>

 Return Multiple Result sets
Return multiple result sets in a single database request, so that you can cut the total time spent communicating with the database. You'll be making your system more scalable, too, as you'll cut down on the work the database server is doing managing requests.

Precompiling a website will enhance the speed because pages do not have to be compiled the first time they are requested
Images Size
Single JavaScript file
Use httpmodule to remove redundant white spaces
Use not more than 3 JavaScript files to decrease the number of HTTP requests between the clients and the server
Use CSS sprites (Combine your background images into a single image)
Avoid Inline JavaScript and CSS
Always make JavaScript and CSS external
Reduce the DOM elements (more divs less tables)
Use Threads

Step 1: Check the Connection Pooling of your project
A connection object is one of the most resource consuming objects in ADO.NET. So we need to manage this object very carefully. Now, opening a new connection and closing it takes a lot of resources. So, rather than creating a connection object again and again, what if we keep a connection object frozen (yes like vegetables) to reuse them later. In the following example I have shown the performance difference of both approaches. In the ConnectionWithPool() function I have used Pooling in the connection string but in ConnectWithoutPool() I did not.

Use Connection Pooling

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Data.SqlClient;
namespace Test1
{
    
class TestConnection
    {
        
public static void ConnectionWithPool()
        {
            
SqlConnection con = new SqlConnection();
            con.ConnectionString = 
"Data Source=.\\SQL_INSTANCE2;Initial Catalog=dbPOSPRO;Integrated Security=True;Pooling=True";
            
for (int i = 0; i < 100; i++)
            {
                con.Open();
                con.Close();
            }
        }
        
public static void ConnectWithoutPool()
        {
            
SqlConnection con = new SqlConnection();
            con.ConnectionString = 
"Data Source=.\\SQL_INSTANCE2;Initial Catalog=dbPOSPRO;Integrated Security=True;Pooling=False";
            
for (int i = 0; i < 100; i++)
            {
                con.Open();
                con.Close();
            }
        }
    }
    
class Program
    {
        
static void Main(string[] args)
        {
            
Stopwatch sw = new Stopwatch();
            sw.Start();
            
TestConnection.ConnectionWithPool();
            sw.Stop();
            
Console.WriteLine("With Pooling: "+sw.ElapsedTicks);
            sw.Restart();
            
TestConnection.ConnectWithoutPool();
            sw.Stop();
            
Console.WriteLine("Without Pooling: " + sw.ElapsedTicks);
            
Console.ReadLine();
        }
    }
}
 
Implement a "Using" block to manage resources properly

Nothing new in here, if you are inexperienced then you have probably heard or read this advice a thousand times. I will also give the same advice in this point but with evidence (read the practical example).

Within the withUsing() function I have implemented a Using block to manage the connection object properly but in the WithuOutUsing() function I did not. Please go through the following code to understand and keep enough courage to see the output screen (Ha ..Ha..).

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Data.SqlClient;
namespace Test1
{
    
class TestConnection
    {
        
public static void WithuUsing()
        {
            
for (int i = 0; i < 10; i++)
            {
                
using (SqlConnection con = new SqlConnection("Data Source=.\\SQL_INSTANCE2;Initial Catalog=dbPOSPRO;Integrated Security=True;Pooling=false"))
                {
                     con.Close();
                }
            }
        }
        
public static void WithuOutUsing()
        {
            
SqlConnection con = null;
            
for (int i = 0; i < 10; i++)
            {
                con = 
new SqlConnection("Data Source=.\\SQL_INSTANCE2;Initial Catalog=dbPOSPRO;Integrated Security=True;Pooling=false");
                con.Open();
                con.Close();              
            }
        }
    }
    
class Program
    {
        
static void Main(string[] args)
        {
            
Stopwatch sw = new Stopwatch();
            sw.Start();
            
TestConnection.WithuUsing();
            sw.Stop();
            
Console.WriteLine("With Using:   "+sw.ElapsedTicks);
            sw.Restart();
            
TestConnection.WithuOutUsing();
            sw.Stop();
            
Console.WriteLine("Without Using: " + sw.ElapsedTicks);
            
Console.ReadLine();
        }
    }
}

Yes, if you manage a resource properly in your program with a Using block then it might enhance performance up to 78 times.

Again, the single line conclusion is "Use using to manage resources and improve performance".

Use local variables in high label of iteration

In a project, looping and heavy iteration is a common scenario. Generally we use for, while or do while loop (yes a foreach loop is internally converted to a for loop) in our code and we initialize the loop counter variable (I, j generally, I also don't know why geek choose I or j rather than the use of the remaining characters. (Ha.. Ha..) It might be similar like class C IP address 192.168 .*.* , No one knows why but people use it.) to go through all iterations.

OK, we are getting off-topic, let's return to the subject. Always make a loop counter variable or other variable local when you are performing some operation within a certain function. I have written the following code to show it practically. Please go through the following code.

class test
{
     
public void loop1()
     {
         
int j = 0;
         
for (int i = 0; i < 250000; i++)
         {
              j = j + 1;
         }
    }
    
int i;
    
int j = 0;
    
public void loop2()
    {        
         
for (i = 0; i < 250000; i++)
         {
              j = j + 1;
         }
    }
}
class Program
{       
     
static void Main(string[] args)
     {
          
test t = new test();
          
Stopwatch sw = new Stopwatch();
          sw.Start();          
          t.loop1();
          sw.Stop();
          
Console.WriteLine("With Loop1:   " + sw.ElapsedTicks);
          sw.Restart();
          t.loop2();           
          sw.Stop();
          
Console.WriteLine("With Loop2:   " + sw.ElapsedTicks);
          
Console.ReadLine();
    }
}

Here is the output screen. We can see that when we define a variable as local (within the function) the performance improves.

LINQ is much slower than other searching techniques

class test
{
     
public void LINQ()
     {
         
int []a = new int[100];           
         
for (int i = 0; i < a.Length; i++)
         {
              a[i] =i;
         }
         
var v = from p in a where p == 70 select p;
     }       
     
public void Linear()
     {
          
int[] a = new int[1000];           
          
for (int i = 0; i < a.Length; i++)
          {
              a[i] = i;
          }
          
for (int i = 0; i < a.Length; i++)
          {
              
if (a[i] == 70)
              {
                  
int b = a[i];
                  
break;
              }
          }
     }
}
class Program
{       
     
static void Main(string[] args)
     {
          
test t = new test();
          
Stopwatch sw = new Stopwatch();
          sw.Start();
          t.LINQ();           
          sw.Stop();
          
Console.WriteLine("With LINQ:   " + sw.ElapsedTicks); 
          sw.Restart();
          t.Linear();           
          sw.Stop();
          
Console.WriteLine("With Search:   " + sw.ElapsedTicks);
          
Console.ReadLine();
     }
}

Our POC result shows the worst searching method is 17 times faster than LINQ. Now, why is LINQ is slower?

LINQ is developer friendly but not performance friendly. It's easy to read and write a LINQ query but internally the LINQ query is converted into a search function and in conversion it requires a lot of resources.

Use the files system to save an image rather than a database.

Choose your data type before using it

Use For loop instead of foreach

List<Int32> Count = new List<int>();
List<Int32> lst1 = new List<Int32>();
List<Int32> lst2 = new List<Int32>();
for (int i = 0; i < 10000; i++)
{
    Count.Add(i);
 }

  Stopwatch sw =new Stopwatch();
  sw.Start();
  for (int i = 0; i < Count.Count; i++)
   {
          lst1.Add(i);
   }
   sw.Stop();

  Console.Write("For Loop :- "+ sw.ElapsedTicks+"\n");
   sw.Restart();

  foreach (int a in Count)
 {
      lst2.Add(a);
  }
 sw.Stop();
 Console.Write("Foreach Loop:- " +  sw.ElapsedTicks);
 Console.ReadLine();

And don't worry, I have tested this example in release mode and this screen shot is taken after several test runs. And still if you want to use a for loop then I will request you to have a look at the output screen shot one more time.
 
Choose when to use a class and when to use a structure

By accepting that you pretty much understand structures and classes in C# or at least in your favorite programming language, if they are present there.

Ok, if you are thinking that "long ago I had learned structures and in daily coding life never used then" then you are among those 95% of developers who have never measured the performance of classes and structures. Don't worry; neither have I before writing this article.


namespace BlogProject
{
   struct MyStructure
    {
       public string Name;
       public string Surname;
    }
   class MyClass
    {
       public string Name;
       public string Surname;
    }
   class Program
    {
       static void Main(string[] args)
        {
           
           MyStructure [] objStruct =new MyStructure[1000];
            MyClass[] objClass = new MyClass[1000];


           Stopwatch sw = new Stopwatch();
            sw.Start();
           for (int i = 0; i < 1000; i++)
            {
                objStruct[i] = newMyStructure();
                objStruct[i].Name = "Sourav";
                objStruct[i].Surname = "Kayal";
            }
            sw.Stop();
           Console.WriteLine("For Structure:- "+ sw.ElapsedTicks);
            sw.Restart();

           for (int i = 0; i < 1000; i++)
            {
                objClass[i] = newMyClass();
                objClass[i].Name = "Sourav";
                objClass[i].Surname = "Kayal";
            }
            sw.Stop();
           Console.WriteLine("For Class:- " + sw.ElapsedTicks);
           
            Console.ReadLine();
        }
    }
}

As we know, structure variables are value types and in one location the value (or structure variable) is stored.

Always use Stringbuilder for String concatenation operations

   public classTest
    {
       public staticstring Name { get;set; }
       public staticString surname;
    }
   class Program
    {
       static void Main(string[] args)
        {
           string First = "A";
            StringBuilder sb = new StringBuilder("A");

            Stopwatch st = new Stopwatch();
            st.Start();
           for (int i = 0; i < 500; i++)
            {
                First = First + "A";
            }
            st.Stop();
           Console.WriteLine("Using String :-" + st.ElapsedTicks);
            st.Restart();

           for (int i = 0; i < 500; i++)
            {
                sb.Append("A");
            }
            st.Stop();
           Console.WriteLine("Using Stringbuilder :-" + st.ElapsedTicks);
           Console.ReadLine();
        }
    }

 

 Choose best way to assign class data member

Before assigning a value to your class variable, I suggest you look at the following code and output screen at this point. 
namespace Test
{
   public classTest
    {
       public staticstring Name { get;set; }
       public staticString surname;
    }
   class Program
    {
       static void Main(string[] args)
        {

            Stopwatch st = new Stopwatch();
            st.Start();
           for (int i = 0; i < 100; i++)
            {
               Test.Name = "Value";
            }
            st.Stop();
           Console.WriteLine("Using Property: " + st.ElapsedTicks);
            st.Restart();
           for (int i = 0; i < 100; i++)
            {
               Test.surname ="Value";
            }
            st.Stop();
           Console.WriteLine("Direct Assign: " + st.ElapsedTicks);
           Console.ReadLine(); 
        }
    }
}


Yes, our output screen is saying that the data member is assigned using a property is much slower than direct assignment.
Are you using exception handling mechanisms for user's input validation?

If yes, then you are the person who is reducing your project execution speed by 62 times. Do you not believe me? Wait a few minutes; I will show you how. But before that example let's learn where exception handling is really necessary.

For example you are validating user's data and for any invalid input you are raising an exception and throwing it to the client (I am assuming you are checking the user's input in business logic) as in the following:
class BusinessLogcCheck
{
    public void Check()
    {
        try
        {
            //Your validation code is here
           
        }
        catch (Exception ex)
        {
            throw new Exception("My own exception");
        }

    }
}

Dear friend, in the next example you will realize how bad the practice is if you see the output screen. Let's see the following code.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
namespace Test1
{
    class Program
    {
        public static void ThrowTest()
        {
            throw new Exception("This is exceptopn");
        }
        public static Boolean Return()
        {
            return false;
        }

        static void Main(string[] args)
        {

            Stopwatch sw = new Stopwatch();
            sw.Start();

            try
            {
                    ThrowTest();
            }
            catch
            {
               
            }
            sw.Stop();
            Console.WriteLine("With Exception " + sw.ElapsedTicks);

            sw.Restart();
            try
            {
                Return();
            }
            catch
            {

            }
            sw.Stop();
            Console.WriteLine("With Return " + sw.ElapsedTicks);
            Console.ReadLine();
        }
    }
}


My proof of concept is very simple. In one function I am raising an exception and in another I am returning a Boolean value after checking the user input. And I have attached a screen of a calculator (Ha Ha..) to make you believe how exception handling impacts code performance.

So, we can draw the one conclusion "Don't raise an exception for user input validation . Use a Boolean return technique (or something like that) to validate input in Business logic". Because exception objects are very costly ones. (But less costlier than your favorite shirt.. Ha Ha.. )

2. Never implement try-Catch within loop.

Yes, It also related to exception handling . I repeat "Never implement try-catch within loop" . Let me prove that it with an example.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
namespace Test1
{
    class Program
    {
        static void Method1()
        {
            for (int i = 0; i < 1000; i++)
            {
                try
                {
                    int value = i * 100;
                    if (value == -1)
                    {
                        throw new Exception();
                    }
                }
                catch
                {
                }
            }
        }
        static void Method2()
        {
            try
            {
                for (int i = 0; i < 1000; i++)
                {
                    int value = i * 100;
                    if (value == -1)
                    {
                        throw new Exception();
                    }
                }
            }
            catch
            {
            }
        }

        static void Main(string[] args)
        {

            Stopwatch sw = new Stopwatch();
            sw.Start();
            Method1();
            sw.Stop();

            Console.WriteLine("Within Loop " + sw.ElapsedTicks);

            sw.Restart();
            Method2();
            sw.Stop();
            Console.WriteLine("Outside of Loop " + sw.ElapsedTicks);
            Console.ReadLine();
        }
    }
}


In this program in method1 I have implemented an exception handling mechanism within the for loop and in method2 I have implemented it without the loop. And our output window is saying that if we implement try-catch outside of the for loop then our program will execute 2 times faster than a try-catch inside the loop.

And again the single conclusion is "Don't implement a try-catch within a loop in your project. (Yes! Not only within a for loop but any loop.)".

3. Are you crazy enough to use the new operator to create an integer variable?

Dear reader, don't criticize me for this long title, and never use the new operator to create a simple integer variable. I know you will argue that if you use the new operator to create a simple integer variable then it will be automatically set to 0 and does not suffer from an error such as "Unassigned local variable" but is it really necessary to get an automatic assignment of 0 where your intention is to create a local variable to store something? Let's see how the new operator degrades performance of code execution.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
namespace Test1
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int i = 0; i < 1000; i++)
            {
                int a = new int();
                a = 100;
            }
            sw.Stop();
            Console.WriteLine("Using New operator:- " + sw.ElapsedTicks);
            sw.Restart();
            for (int i = 0; i < 1000; i++)
            {
                int a;
                a = 100;
            }
            sw.Stop();
            Console.WriteLine("Without new operator:- "+ sw.ElapsedTicks);
            Console.ReadLine();
        }
    }
}



Yes the new operator degrades execution speed 5 times. Hmm.. Sourav, I can deny the output screen but one thing!! You are creating 1000 variables at a time; in our project we won't create 1000 variables at a time, the maximum we will create is two or three.

Ok. Is your application a web application? If yes then please check the hit count of any popular web application and I am sure it's more than 1000 per day.

Again the single line conclusion "Don't be crazy enough to use the new operator to create an integer variable".

4. Choose best collection according to your purpose

We .NET developers are very much familiar with collections in C# and their use here and there to store values. Let's see how they perform for searching. See the performance of searching for an integer number. Here is my code.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
namespace Test1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<Int32> li = new List<Int32>(1000);
            Dictionary<intint> di = new Dictionary<intint>(1000);
            int[] arr = new int[1000];
            int a;
           
            for (int i = 0; i < 1000; i++)
            {
                li.Add(i);
                di.Add(i, i);
                arr[i] = i;
            }

            Stopwatch sw = new Stopwatch();
            sw.Start();
            a = li[500];
            sw.Stop();
            Console.WriteLine("From list:- " + sw.ElapsedTicks);


            sw.Start();
            a = arr[500];
            sw.Stop();
            Console.WriteLine("From Integer array:- " + sw.ElapsedTicks);


            sw.Restart();
            a = di[500];
            sw.Stop();
            Console.WriteLine("From Dictionary:- " + sw.ElapsedTicks);
            Console.ReadLine();
        }
    }
}
 Function is good , but not all time

If you remember you're first few days of learning programing, you learned the one concept of always implementing a function to implement good practices in code and yes really it's good to implement a function to perform certain tasks. There are thousands of advantages of functions in programming but let's see how a function degrades performance of execution. Again I am saying, this point is not against functions but to show you simply how function calling is a costly mechanism and provides an idea of where to implement a function and where not to. Let's see the following code.
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
namespace Test1
{
    class test
    {
        public static void Print()
        {
            Console.WriteLine("I am function from Class");
        }
    }


    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            test.Print();
            sw.Stop();
            Console.WriteLine(sw.ElapsedTicks);

            sw.Restart();
            Console.WriteLine("I am single statement within main");
            sw.Stop();
            Console.WriteLine(sw.ElapsedTicks);

            Console.ReadLine();
        }
    }
}




Here I want to print a single message in the output window and at first I have implemented it within a static function and call it by class name and the second time I have just written it within the main function. Yes very simply by Console.Writeline(). And the output screen is saying that the single line execution is 9 times faster than the function. And obviously we will not start the debate of the topic "Advantages and disadvantages of functions" ( Ha Ha..).


If possible use a static function

Yes, if possible try to implement a static function because static objects (both function and data) does not belong to any object of a particular class. It's common to all. So if you do not create an object then there is no question of memory consumption. In the following I am showing one example of a static function and static class. And have a look at the IL code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Net.NetworkInformation;
using System.Threading;
using System.Globalization;
using System.Data.SqlClient;
namespace Test1
{
    
public static class mySclass
    {
        
public static void Print()
        {
            
Console.Write("Hello");
        }
    }
    
public class myNclass
    {
        
public static void Print()
        {
            
Console.Write("Hello");
        }
    }
    
class Program
    {
        
static void Main(string[] args)
        {
            
for (int i = 0; i < 1000; i++)
            {
                
mySclass.Print();
                
myNclass.Print();
            }
        }
    }
}


So, in a single line the conclusion is "If possible try to create a static function and invoke with the class name rather than invoking the general function by object name".

How you check empty string in your code?

In this point I am going to show you three empty or null string checking styles. I hope you are familiar with all styles but may not familiar with their performance. Let's start with a small example. In the following there are three functions (Yes all static. I am lazy, and don't want to create the object again). In the first style I am using the Length property. In the second I am using a space or empty string (" "). And in the third case I am using an Empty property of the string class. The following is my test code.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace Test1
{
    public class Compare
    {
        public static void First(string Value)
        {
            if (Value.Length != 0)
            {
              
            }
        }

        public static void Second(string Value)
        {
            if (Value != "")
            {

            }
        }
        public static void Third(string Value)
        {
            if (Value != string.Empty )
            {

            }
        }
        }
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            Compare.First("Sourav");
            sw.Stop();
            Console.WriteLine("Using Length: "+sw.ElapsedTicks);

            sw.Restart();
            Compare.Second("Sourav");
            sw.Stop();
            Console.WriteLine("Using !=     " +sw.ElapsedTicks);

            sw.Restart();
            Compare.Third("Sourav");
            sw.Stop();
            Console.WriteLine("Using Empty: " + sw.ElapsedTicks);

           
            Console.ReadLine();
        }
    }




So, the single line conclusion "Use of String.Empty to check whether the string is null or not".

Change your style of type casting

Yes, change it if you are not implementing the proper type casting technique. In the following I show two traditional styles of type casting and their performance impact on code. The first style (and the worst) is very simple, by using parenthesees () used by most of developers. And the second style is by the as keyword. In the following code I have implemented both of them. Let's go through the following code.
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace Test1
{
    public class Base
    {
    }
    public class Derive : Base
    {
    }

    class Program
    {
        static void Main(string[] args)
        {

            Derive d = new Derive();

            Stopwatch sw = new Stopwatch();

            sw.Start();
            Base b =(Base) d;
            sw.Stop();
            Console.WriteLine("Using type cust : "+ sw.ElapsedTicks);

            sw.Restart();
            Base c = d as Base;
            sw.Stop();
            Console.WriteLine("Using as keyword : "+ sw.ElapsedTicks);
            Console.ReadLine();
        }
    }
}




Efficient string comparison method

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace Test1
{
    public class Test
    {
        public static void First(String Value)
        {
            for (int i = 0; i < 100; i++)
            {
                if (Value == "Sourav")
                {
                    continue;
                }
            }
        }
        public static void Second(String Value)
        {
            for (int i = 0; i < 100; i++)
            {
                if (Value.Equals("Sourav"))
                {
                    continue;
                }

            }
        }
   }
   
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            Test.First("Sourav");
            sw.Stop();
            Console.WriteLine("Using == : "+ sw.ElapsedTicks);

            sw.Restart();
            Test.Second("Sourav");
            sw.Stop();
            Console.WriteLine("Using Equals : "+ sw.ElapsedTicks);

           
            Console.ReadLine();
        }
    }
}


You I have an attached calculator for quick calculation (Ha..Ha..). And the screen shows that the use of the "==" style is 190 times slower than the String comparison function (Equals()). Again I am not going to write single line conclusion. It's your responsibility to change your style and share the image above (output screen) to your friend in a lazy coffee break.

4. Impalement for loop with a little trick

Before starting I want to let you know something. It's not a very important point. Or it will be a very important trick to adapt. Here I will show how to implement our traditional for loop with a little spice. If you go through the following code then you will find in the second "for" implementation a local variable is using fewer times and that's why consumtion is less time but not very less. So, it's a best practice to use a variable less number of times.
 
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace Test1
{
    public class Base
    {
        public static void First(Int32 limit)
        {
            for (int i = 0; ++i <= limit; )
            {
            }
        }
        public static void Second(Int32 limit)
        {
            for (int i = limit; -- i >= 0; )
            {
            }
        }
    }
    class Program
    {
        static void Main(string[] args)
        {

            Stopwatch sw = new Stopwatch();

            sw.Start();
            Base.First(100);
            sw.Stop();
            Console.WriteLine("First "+ sw.ElapsedTicks);

            sw.Restart();
            Base.Second(100);
            sw.Stop();
            Console.WriteLine("Second : "+ sw.ElapsedTicks);

           
            Console.ReadLine();
        }
    }
}





Inheritance is a good practice but not always

We know one beautiful feature of OOP is inheritance, and it reduces code redundancy, improves code maintenance and so on. I am not denying them but my fifth point is against unnecessarily creating small classes here and there. If it is really not needed then don't create a class hierarchy. Have a look at the following code.
 
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
namespace Test1
{
    public class Base
    {
    }
    public class Derive  :Base
    {
        public string name;
    }

    public class Concrete
    {
        public string name;
    }

    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();

            sw.Start();
            Derive d = new Derive();
            d.name = "Sourav";
            sw.Stop();
            Console.WriteLine("Derive style : "+ sw.ElapsedTicks);

            sw.Restart();
            Concrete c = new Concrete();
            c.name = "Sourav";
            sw.Stop();
            Console.WriteLine("Concrete class : "+ sw.ElapsedTicks);

            Console.ReadLine();
        }
    }
}

At first I created two small classes and between them I am not at all using the first one. It's serving as base class. In the second scenario I have created a single concrete class; there is no concept of inheritance on it. And within the main () method I am creating an object of both of them. Let's see the output screen.

Let's conclude with the single line comment "Don't implement class hierarchy if not needed."