In Focus

Smart Coding, Think Memory

I have noticed, some programmers define variables for no reason. By using this quick tip, we can write more cleaner and efficient code.

OK, this type of code I see every where. Many of us write this code every day.

Take a look at this below code? 

// Create new instance of a DataSet

DataSet ds = new DataSet();

// Get data from a database

ds = GetData();

// Display Data

DataGrid1.DataSource = ds;


Now what is wrong with this above code? Absolutely nothing. We are creating a DataSet, filling it by calling a method GetData and binding it to a DataGrid.


Now, what if I replace the above code with this one line?


DataGrid1.DataSource = GetData();


Now both code are doing exactly same thing but the problem with first code snippet is, it is creating a DataSet object, which is not required at all. 


By using second code snippet, we not only reduced the size of code and file, we also avoided creating a new DataSet object.

Still not clear? Let's think this way. I want to eat a Donut. In first case, I go to Dunkin Donuts, buy a donut, put in a plate and eat it. In second case, I buy a donut and direct eat it. In second case, not only I avoided use of a plate, I also avoided the execution time taken between dount and plate and plate and my mouth :-). 


Remember, every time you define a variable, somewhere, memory space is being allocated for that variable. No matter for how long you use it, it will still be extra overhead on the processor.


Here is one more example:


string str = "My String"; 
TextBox1.Text = str;


It can easily be replaced with this:


TextBox1.Text = "My String";  


The second code is more efficient than the previous one.