How to improve the performance of a foreach

Asked

Viewed 426 times

3

I’m consuming a webservice, that has at least 5557 records.

The problem is after consuming. I have to add in my database the records, and for that, I have to do a foreach, what ends up disturbing a little the performance, taking on average 5 minutes.

How do I get better?

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();
  • There’s not much to do there. You can probably do something at MunicipioListar.

  • That’s what I thought, @mustache, but I can’t touch that method.

1 answer

1

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

Try turning off Autodetectchanges by setting the attribute AutoDetectChangesEnabled for false, thus:

_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;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.