Share via


Optimization through Generics

Generics, apart from providing type-safety at compile time, does come with a lot of other goodies which .NET developers might have got used to by now. Some of its other well known advantages are reusable code, improved performance by negating boxing (by product of the feature mentioned above).  

During an internal code review process I came across the following snippet of code, which drives home the point which I was trying to make above:

List<string>[] lstCheckedMonths = this.treeView.GetCheckedNodesByLevel(3);

 

string[] fiscalMonths = lstCheckedMonths[2].ToArray();

 

int[] intfiscalMonths = new int[fiscalMonths.Length];

 

for (int i = 0; i < fiscalMonths.Length; i++)

{

    intfiscalMonths[i] = Convert.ToInt32(fiscalMonths[i]);

}

 

Array.Sort(intfiscalMonths);

 

bool valid = true;

 

for (int i = 1; i < intfiscalMonths.Length; i++)

{

    if (intfiscalMonths[i] != intfiscalMonths[i - 1] + 1)

    {

        valid = false;

        break;

    }

}

This code is basically duplicating the same chunk of data from lstCheckedMonths into arrays fiscalMonths, intfiscalMonths. Now let us see how this code can be efficiently written using Generics thereby optimizing for performance and increasing code readability:

List<string>[] lstCheckedMonths = this.treeView.GetCheckedNodesByLevel(3);

 

List<int> fiscalMonths = lstCheckedMonths[2].ConvertAll<int>(StringToIntConverter);

 

fiscalMonths.Sort();

 

bool valid = true;

 

for (int i = 1; i < fiscalMonths.Length; i++)

{

    if (fiscalMonths[i] != fiscalMonths[i - 1] + 1)

    {

        valid = false;

        break;

    }

}

The above code does avoid copying over of the same data and instead manages with one array fiscalMonths. The code now goes onto become more readable. The key here, as you probably might have realized by now, is the ConvertAll<int >(StringToIntConverter) method which is using a simple delegate StringToIntConverter to perform the conversion.

Pretty slick huh!!