Reputation: 43873
Say I have:
using (SomeDataContext db = new SomeDataContext())
{
foreach(Item i in Items)
{
DbItem d = new DbItem;
d.value = i.value;
//.... etc ...
db.InsertOnSubmit(d);
}
db.SubmitChanges();
}
Is it possible and/or better (worse?) to do:
using (SomeDataContext db = new SomeDataContext())
{
IEnumerable<DbItem> dbItems = //???? possible?
foreach(Item i in Items)
{
DbItem d = new DbItem;
d.value = i.value;
//.... etc ...
dbItems.Add(d); // ???? again, somehow possible?
}
db.InsertAllOnSubmit(dbItems);
db.SubmitChanges();
}
Upvotes: 8
Views: 9240
Reputation: 28728
You won't see any performance improvement here, because nothing happens until you call SubmitChanges()
.
But even if you were doing something ugly like this
foreach(Item i in Items)
{
DbItem d = new DbItem;
d.value = i.value;
//.... etc ...
db.InsertOnSubmit(d);
db.SubmitChanges();
}
I wouldn't expect any significant performance decrease. This is because LINQ-to-SQL does singular inserts.
Even if you use InsertAllOnSubmit
, you'll still see a separate SQL Command for each row being inserted.
Upvotes: 4
Reputation: 51
Not saying that it is better or worse but anytime you can make a single database call vs. calling a database in a loop you will see a performance increase. Now what .SubmitChanges()
does behind the scenes is something out of our control.
Upvotes: 2
Reputation: 1502376
Well you could use List<T>
:
using (SomeDataContext db = new SomeDataContext())
{
List<DbItem> dbItems = new List<DbItem>();
foreach(Item i in Items)
{
DbItem d = new DbItem;
d.value = i.value;
//.... etc ...
dbItems.Add(d);
}
db.InsertAllOnSubmit(dbItems);
db.SubmitChanges();
}
Whether that will be any more efficient or not, I don't know.
Upvotes: 13