ANSWER: POP QUIZ: What’s wrong with this code – part 3

This issue is an interesting one in that there are more then one problem here that will cause high memory and even what looks to be a problem that will affect the performance of this snippet as well.

So the two main problems are that we are using XSLT.Load inside of a loop which means that we are going to create a new dynamic assembly for each loop iteration.  The other problem is string concatenation.  Instead of using the + to build our string in each loop, we should use StringBuilder to save on memory.

These two issues are documented here:

As for the other issue in this code, we declare our loop iterator outside of the for loop.  This isn’t a problem and doesn’t cause any slowness, but if we were to have used an Array and looped through the objects of the array, we could have run into the “Range Check Elimination” optimization.  Take a look here for more information on that.  Basically, this code:

 ArrayList myArray1 = new ArrayList();
PopulateArray(myArray1);

for (int i = 0 ; i < myArray1.Count ; i++)
{
  // Do Stuff
}

Is faster then this is:

 ArrayList myArray2 = new ArrayList();
PopulateArray(myArray2);

int iCount = myArray2.Count;
for (int i = 0 ; i < iCount ; i++)
{
  // Do Stuff
}

Because in the first case, we don’t have to check that we haven’t gone past the bounds of the array.