For Experts Only

time to read 2 min | 349 words

There are some things that programmers really shouldn't do. I was once called to help figuring out why a batch process would run for a few hours at 100%. The previous guy has claimed that this was a natural occurance of the task at hand (loading XML file to DB), and that he had already optimized it as far as possible.

int count = 0;
XmlDocument xdoc = new XmlDocument();
xdoc.Load(filePath);

foreach(XmlNode node in xdoc.SelectNodes("data/row")) 
{
   count++;
   new Thread(delegate(object state){
        XmlNode n = (XmlNode)state;
        using(SqlConnection con = new SqlConnection("... "))
        using(SqlCommand cmd = con.CreateCommand ())
        {
            cmd.CommandText = "INSERT INTO .... ";
            cmd.ExecuteNonQuery();
        }
        Interlocked.Decrement(out count);
   }).Start(node);
}

while(count!=0); 

After de-optimizing the code, I managed to get 10,000% performance improvement, and you could actually use the server for more than a single task.