【问题标题】:Fastest way to add a Range in a List C#在列表 C# 中添加范围的最快方法
【发布时间】:2021-12-16 19:05:15
【问题描述】:

我必须将大约 3000 个元素添加到超过 20 个列表中。 我正在使用的代码:

LastChange = new List<string>();
LastChange.AddRange(Enumerable.Repeat("/", 3000));

same for more than 20 Lists...

是否有任何“最快的方法”将“/”添加到列表中,或者这是最好的解决方案。提前致谢...

【问题讨论】:

  • LastChange = new List&lt;string&gt;(3000); 会好一点:我们为3000 项目分配内存以避免动态重新分配
  • @DmitryBychenko 谢谢。你能写出完整的答案吗?!
  • 为什么不LastChange = Enumerable.Repeat("/", 3000).ToList()?当您的列表不是现有列表时,我真的不明白使用AddRange 的意义

标签: c# list optimization


【解决方案1】:

更好的解决方案是在构造函数中为3000 项分配内存以避免内存重新分配:

 LastChange = new List<string>(3000);

 LastChange.AddRange(Enumerable.Repeat("/", 3000)); 

你可以更进一步,在Enumerable.Repeat中去掉IEnumerator&lt;T&gt;

 int count = 3000;

 LastChange = new List<string>(count);

 // compare to 0 is a bit faster then 3000
 for (int i = count - 1; i >= 0; --i)
   LastChange[i] = "\";        

【讨论】:

    猜你喜欢
    • 2012-08-05
    • 2016-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-23
    • 2010-11-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多