Question

Within a C# project, I need to fill an Access 2010 database with a lot of data, where performance is an issue. I did some testing using various data access techniques, and found out that using old fashioned DAO gives me the best performance (using a code example I found here on Stackoverflow). The code below takes about 2.5 seconds to fill a 6-column table with 100,000 records.

Dao.DBEngine eng = new Dao.DBEngine();
Dao.Database db = eng.OpenDatabase(@"d:\temp\speedtest.accdb");
eng.BeginTrans();

Dao.Recordset rs = db.OpenRecordset("tblTest");
Dao.Field[] myFields = new Dao.Field[6];
for (int k = 0; k <= 5; k++) {
    myFields[k] = rs.Fields[k];
}

for (int i = 1; i <= 100000; i++) {
    rs.AddNew();
    myFields[0].Value = i;
    myFields[1].Value = i;
    myFields[2].Value = i;
    myFields[3].Value = i.ToString();
    myFields[4].Value = i.ToString();
    myFields[5].Value = i.ToString();
    rs.Update();
}

eng.CommitTrans();

Out of curiosity, I rewrote this piece of code, line by line, in VB.net.

Dim eng As New Dao.DBEngine()
Dim db As Dao.Database = eng.OpenDatabase("d:\temp\speedtest.accdb")
eng.BeginTrans()

Dim rs As Dao.Recordset = db.OpenRecordset("tblTest")
Dim myFields() As Dao.Field = New Dao.Field(5) {}
For k As Integer = 0 To 5
    myFields(k) = rs.Fields(k)
Next

Dim startTime As DateTime = DateTime.Now
For i As Integer = 1 To 100000
    rs.AddNew()
    myFields(0).Value = i
    myFields(1).Value = i
    myFields(2).Value = i
    myFields(3).Value = i.ToString()
    myFields(4).Value = i.ToString()
    myFields(5).Value = i.ToString()
    rs.Update()
Next

eng.CommitTrans()

The VB.net version runs in about 0.26 seconds or roughly 10 times faster than the C# version. I find this difference staggering, and I can not explain this. When I look at the IL code with Reflector, I can see no noticeable differences. The projects are equal (both console applications), with the code above in the main method. Anyone any ideas how to get the C# version on the same performance?

Was it helpful?

Solution

First of all, thanks to everyone who provided me with helpful hints and advice. I found the reason why the C# program was performing so badly, compared to it's VB counterpart.

If the C# code had been written as part of the 'normal' development solution, I would never have had this problem. But unfortunately, when you start a C# console project, the main method does not get the [STAThread] attribute. I haven't figured out yet why a console program is lacking this attribute by default, but when added to my example program the C# and VB code perform exactly the same (give or take a few milliseconds).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top