c# – How to improve the performance of a foreach

Question:

I'm consuming a webservice , which has at least 5557 records.

The problem is after consuming. I have to add the records to my database, and for that, I have to do a foreach , which ends up hampering performance a little, taking an average of 5 minutes.

How do I improve?

var tb_municipio_ws = _ServiceReaderClient.MunicipioListar();

if (tb_municipio_ws.Items != null || tb_municipio_ws.Item != null)
{
    foreach (var item in tb_municipio_ws.Items)
    {
        var tbMunicipios = new TB_MUNICIPIOS
        {
            MUN_ID = item.MunId,
            /*
            ....
            */
        };
        _context.TB_MUNICIPIOS.Add(tbMunicipios);
    }
}
_context.SaveChanges();

Answer:

Probably the cause of the slowness is not just the call to the webservice, because even with the data available locally, the Entity Framework would continue to check changes (DetectChanges) for each record included. The more records, the slower this check becomes.

Try turning off AutoDetectChanges by setting the AutoDetectChangesEnabled attribute to false , like this:

_context.Configuration.AutoDetectChangesEnabled = false;

if (tb_municipio_ws.Items != null || tb_municipio_ws.Item != null)
{
    foreach (var item in tb_municipio_ws.Items)
    {
        var tbMunicipios = new TB_MUNICIPIOS
        {
            MUN_ID = item.MunId,
            /*
            ....
            */
        };
        _context.TB_MUNICIPIOS.Add(tbMunicipios);
    }
}
_context.SaveChanges();

_context.Configuration.AutoDetectChangesEnabled = true;
Scroll to Top