Which is faster: clear collection or instantiate new

后端 未结 8 925
遇见更好的自我
遇见更好的自我 2020-12-01 06:26

I have some number of generic lists in my code, that have tens or hundreds elements. Sometimes I need to refill this lists with other objects, so question is: what will be f

8条回答
  •  伪装坚强ぢ
    2020-12-01 06:28

    Maybe I'm doing something fundamentally wrong here but while developing an ASP.NET application in C# I'm encountering quite a difference when using Clear() vs. new. I'm creating a statistics page with charts, which have data series. For each chart I have a section where I do this:

    chart = new ChartistChart() { Title = "My fancy chart" };
    series = new List();
    *some code for getting the statistics*
    chart.Series.Add(series);
    chartistLineCharts.Add(chart);
    

    then another chart follows.

    chart = new ChartistChart() { Title = "My second fancy chart" };
    series = new List();
    *some code for getting the statistics*
    chart.Series.Add(series);
    chartistLineCharts.Add(chart);
    

    This works just fine with series being reallocated with new, but when I do

    series.Clear();
    

    instead I actually clear the entry inside chart.Series and chartistLineCharts so the statistics page ends up retrieving only the last chart's series. I assume there is some link, like a memory pointer, here and this is a different issue than what is originally discussed, but this is at least a reason to pick new over Clear(). Perhaps there is a way to avoid it though.

提交回复
热议问题