C#- Performance of code – For loop vs For each Loop

I had a small experiment to prove the point under discussion, I have a table accounts in SQL Server database, I added  20000 rows into the table with 9 columns and approximately 1 Kilobyte of data per record. After loading into my Business layer i am converting it back to a DTO, and returning to my web service. Just to test the performance I added two performance counters, one for “for each” loop and one for “for loop”, The results are obvious, foreach loop took 107 milliseconds to execute the same process, while classic for loop took 14 milliseconds.

forloop-blog-1

Now why does this happen, lets get a bit deeper.

The for loop version uses enough stack space for only two local variables (counter and i). The Foreach version uses stack space for four locals (item, AccountList object, and two compiler-generated temporaries).

When a method is called in the CLR, all of the memory required for the locals is allocated upon the stack. As this takes place on the stack, this process is fast, but it is not free. That is why the foreach-loop will incur a small cost due to its extra two local variables.

WAIT !!!

There is something else, which changes the effect.

If we use the local variable multiple times in for loop and foreach loop, see what happens.

forloop-blog-2

The game is reversed, that means that if we have to access the local variable value multiple times in the for loop, in that case the performance will decrease.

Deductions

a- This for-each loop is faster because the local variable that stores the value of the element in the array is faster to access than an element in the array.

b- The for-loop is faster than the foreach-loop if the array must only be accessed once per iteration.

knockoutjs and MVVM

MVVM ( Model View ViewModel ) is a new architechture that is heavily followed in mainstream enterprise frameworks these days along with other frameworks. I’ll talk less about this and talk more about knockoutjs in this post. Knockout is an extraodrinary library, which if fully utilized in its best way, it can be very efficient and day saver in the end.

You can get more info about knockoutjs here at http://knockoutjs.com/

I’ll follow through a scenerio how we can utilize knockoutjs library in the simplest way possible.

Say, we have a webservice that is returning us some Json data. We want to pull data out of it and bind to our controls back there in the html form. Lets do it here.

Suppose our html is like this:

<p>First name: <input data-bind="value: firstName" /></p>
<p>Last name: <input data-bind="value: lastName" /></p>
<h2>Hello, <span data-bind="text: fullName"> </span>!</h2>
Now we see that we provided just some databind attributes to the input controls. What we want is that when user adds firstname or lastName in the text boxes, it should concat those and display those in the <h2> tag which we have binded with fullName.
One classic approach would be to declare a onkeydown event on both first name and last name and in the event declaration, we can concat and set it into fullName block. For that we have to declare some extra stuff like we have to id-fy our controls, declare events, write some javascript.
Lets see a more savvy approach!
We will reference knockoutjs lib in the page, and in script portion write the following code (btw we can do the same code in seperate js file as well for clean seperation of code):
// Here's my data model
var ViewModel = function(first, last) {
    this.firstName = ko.observable(first);
    this.lastName = ko.observable(last);
    this.fullName = ko.computed(function() {
        // Knockout tracks dependencies automatically. It knows that fullName depends on firstName and lastName, because these get called when evaluating fullName.
        return this.firstName() + " " + this.lastName();
    }, this);
};
ko.applyBindings(new ViewModel("Planet", "Earth"));

What we have done here is we created a view model, and we created firstName and lastName properties in it, and ensured the two way binding through ko.observable(first). And for the replacement of javascript keydown event we have done it in a more cleaner way by making a computed function fullName.

In the end i called ko.appyBindings() function that does all the magic to bind my form with my viewModel and with event notifications to and fro.
Knockoutjs is a great library and with a great future ahead. I will be posting more on this so keep looking.

Software Design Approach Level zero

“Give me good mothers, and i will give you good nation”.

This napolean law applies somewhat to software industry as well, i say “Give me good software design and i will deliver good software”

A good software design requires a lot to think and endevour. Few things are as below:

– Solve the big question “Why?”, if we clear the why in our software while designing, we are half way done.

– Team balancing and satisfaction ( Mostly we do not care about this )

– Not everyone is a good software designer. Choose wisely, else the project will be spinning in facade, unity, singleton.. and what not

–  Make the base strong.. If your base is not strong, you can also hang your project in air with just one charisma. and that is “Communication”. Keep in line with your client at all time. Do not let him loose you and vise versa.

– Do not go for complex architectures, which just makes you geeky and give you an extra raise at the end of year. This stunt does works, but can elongate or sometimes destroys the projects.

– Ask your developer at least  once that they want to do the job or not, do not be impositive.

– Do not  cheat, bluff, over show, or give false committments to your client at all.

– Keeping all points above in mind.. Now guys, design your software at last.

Happy Software designing.