开发者

Simple Basic Question

Sorry for asking such a simple question but wanted to clear a concept.

Below is my code where I am creating a dictionary inside for loop

if(condition)
{
  // some code here
  for(int i=0; i<length; i++)
  {
    Dictionary<string, string> parameter = new Dictionary<string, string>();
    parameter.Add("ServiceTypeID", "1");
    parameter.Add("Description", "disc");
  }
}

instead of creating dictionary object every tim开发者_开发百科e should I be creating the dictionary object before for loop and applying clear method on dictionary object like

if(condition)
{
  Dictionary<string, string> parameter = new Dictionary<string, string>();
  // some code here
  for(int i=0; i<length; i++)
  {
    parameter.clear();
    parameter.Add("ServiceTypeID", "1");
    parameter.Add("Description", "disc");
  }
}

Out of these two option which one will be better for performance.

Thanks, nil


In most practical scenarios the difference is close to zero.

One may think that clearing a data structure is quicker than initializing an empty one. This is not always the case. Note that modern languages (C#, Java) the memory manager is optimized for allocating many small objects (this is related to the way Garbage Collectors work). In C++, due to the lack of a GC, the memory manager is tuned to allocation of few large objects. Thus, re-constructing the Dictionary inside the loop is comparable (performance-wise) with clearing it.

Moreover, clear() may not necessarily free all allocated memory. It can be that it only resets some pointers/indices. Therefore, if you use clear() your Dictionary may still occupy large chunks of memory which may slow down other parts of your code.

Bottom line: don't worry about it unless a profiler told you that this is the bottleneck of your program.


If both of these solutions are working for you you should remember two items :

  • first one creates dictionary object in each loop, so its speed is lower because of allocating memory in each loop times
  • second one is faster. but takes the Dictionary object alive for more time, so memory will be full if GC takes no action on it! (GC removes it after scope ends) so in long blocks of code, takes the memory in use for more time!


In few words for the performance, clearly, the second loop is better because you create only one object and then in the loop you add items.

However in the first loop parameter variable is not useful because at the end of the for it does not exists any more...

also in the second loop you have the same problem... at the end of the if that reference isn't usable....

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜