哪个更快:清除集合或实例化新的 [英] Which is faster: clear collection or instantiate new

查看:13
本文介绍了哪个更快:清除集合或实例化新的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码中有一些通用列表,其中包含数十或数百个元素.有时我需要用其他对象重新填充这个列表,所以问题是:调用 Clear() 方法或创建一个 new List() 会更快?

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 faster, to call Clear() method or creating a new List<T>()?

推荐答案

什么会更快,调用 Clear() 方法还是创建一个 `new List()?

what will be faster, to call Clear() method or creating a `new List()?

这是不可能回答的.这真的取决于很多因素,包括收藏的存在时间.

This is impossible to answer. It really depends on a lot of factors, including how long the collection has existed.

这里最好的选择是:

  1. 分析应用程序,看看这是否真的很重要.它可能不会产生任何可察觉的差异,在这种情况下,我会使用对您如何看待这个对象最有意义的方法.

  1. Profile the application, and see if this really matters. It likely won't make any perceptible difference, in which case, I'd use the method that makes the most sense in terms of how you think of this object.

如果确实重要,请编写两组代码,并测量速度差异(如果有).

If it does matter, write both sets of code, and measure the difference in speed (if any).

从实际的角度来看,调用 Clear() 实际上不会减少内存(由 List 本身使用),因为它不会缩小列表的容量,只消除其中包含的值.创建一个新的 List 将导致分配一个新列表,这反过来又会导致更多的分配随着增长而增加.

From a practical perspective, calling Clear() will not actually reduce the memory (used by the List<T> itself), as it doesn't shrink the list's capacity, only eliminates the values contained within it. Creating a new List<T> will cause a new list to be allocated, which will in turn cause more allocations with growth.

然而,这并不意味着它会变慢 - 在许多情况下,重新分配会更快,因为您不太可能将大型数组提升到更高的垃圾收集代,这在turn 可以使 GC 过程保持更快.

This, however, does not mean that it will be slower - in many cases, reallocating will be faster as you're less likely to promote the large arrays into higher garbage collection generations, which in turn can keep the GC process much faster.

如果不知道您的确切场景并在分析器中测量,就无法知道哪个更适合您的场景.

Without knowing your exact scenario and measuring in a profiler, there is no way to know which is better in your scenario.

这篇关于哪个更快:清除集合或实例化新的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆