简体   繁体   中英

Declaring objects within or outside the loop

I have a parallel loop that checks around 1 mil records in the database and sends many requests to the database. I re-declare the new DB object on each parallel loop iteration.

DataSet ds = new psqlWork().getDataSet("SELECT * FROM z_sitemap_links");
DataTable dt = ds.Tables[0];
Parallel.ForEach(dt.AsEnumerable(), dr =>
{
    new Sitemap().runSitemap(dr[1].ToString(), counter);
    counter++;
});

Is it proper to declare the new Sitemap() object outside the loop, or on each execution?

The meaning of the code is totally different in these 2 cases, not sure why this "performance" question...

If your object is shared across all iterations - declare outside and share. Otherwise declare locally.

I would declare it INSIDE the loop. Always declare everything at the exact point it's needed. It makes your code neater and easier to refactor.

Only even bother thinking about performance if you notice the system is too slow, then use a profiler to find out where it's slow and improve one thing at a time.

Well, it depends on what the object does. If the object's state is altered at any point, it needs to stay in the loop. Otherwise, you could declare it outside to save some allocations.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM