locked
It's better to redeclare and redefine Objects or declare once and define multiple time RRS feed

  • Question

  • if(true){DataTable dt = somevalue;}

    if(true){DataTable dt = somevalue;}

    if(true){DataTable dt = somevalue;}

    or

    DataTable=null;

    if(true){ dt = somevalue;}

    if(true){ dt = somevalue;}

    if(true){ dt = somevalue;}

    Which one is most preferable in terms of performance

    if we go for of type int/string or any Object what difference will b there.

    Friday, January 10, 2014 10:22 AM

Answers

  • Well, would you have made a meaningful example, then the compiler would already have told you the important difference.

    namespace ConsoleApplication4
    {
        using System;
        using System.Data;
       
        public class Program
        {
            static void Main(string[] args)
            {
                const DataTable somevalue = null;
    
                if (true) { DataTable dt1 = somevalue; }
                if (true) { DataTable dt1 = somevalue; }
                if (true) { DataTable dt1 = somevalue; }
    
                if (dt1 != null)
                {
                    dt1.Clear();
                }
                
    
                DataTable dt2 = null;
                if (true) { dt2 = somevalue; }
                if (true) { dt2 = somevalue; }
                if (true) { dt2 = somevalue; }
                
                if (dt2 != null)
                {
                    dt2.Clear();
                }
    
                Console.ReadLine();
            }
        }
    }
    

    While object creation is always considered to be a slow operation, it is not important for DataTables under normal circumstances.

    Thus in respect to Don Knuth: 1. Make it run, 2. make it right, 3. make it fast. Premature optimization..

    Friday, January 10, 2014 10:34 AM