Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to SQL loop performance

OK, I have a bunch of complex logic I need to iterate through. I am calling a web service and getting back results. I take the results and loop through them and make different database calls based on various rules.

The initial code I used was the following:

foreach(var obj in MyObjects)
{
    using(var connection = new LinqToSqlDBContext())
    {
        connection.StoredProc1(obj.Name);
        connection.StoredProc2(obj.Name);
        connection.SubmitChanges();
    }
}

I figure this would be more efficient:

using(var connection = new LinqToSqlDBContext())
{
    foreach(var obj in MyObjects)
    {
        connection.StoredProc1(obj.Name);
        connection.StoredProc2(obj.Name);       
    }
    connection.SubmitChanges();
}

Is there a better way I can do this to increase performance? I am using Linq to SQL classes and C# 4.0.

Thanks!

like image 956
Cyberdrew Avatar asked Dec 27 '22 13:12

Cyberdrew


1 Answers

Since you are invoking stored-procs, but not performing object changes, the SubmitChanges() is redundant. In normal usage, I would expect this SubmitChanges to be a significant factor, so balancing the number of calls vs the size of individual transactions is important. However, that doesn't apply here, so I would just use:

using(var connection = new LinqToSqlDBContext())
{
    foreach(var obj in MyObjects)
    {
        connection.StoredProc1(obj.Name);
        connection.StoredProc2(obj.Name);       
    }
}
like image 131
Marc Gravell Avatar answered Jan 11 '23 13:01

Marc Gravell