这是更快:明确收集或实例化新这是、更快、实例、明确

2023-09-02 11:52:27 作者:臣服心动

我在code泛型列表,有几十或几百元的一些数字。 有时候,我需要补充与其他物体这个名单,所以问题是:什么会更快,叫清除()方法,或创建一个新名单,其中; T>?()

解决方案   

这将是更快,调用Clear()方法或创建一个新的列表()?

这是不可能回答。这真的取决于很多因素,包括多长时间的收集一直存在。

这里最好的办法是:

个人的应用程序,看看这个真的很重要。它可能不会做出任何明显的差异,在这种情况下,我会使用的最有意义的,你如何看待这个对象方面的方法。

如果它的问题,写两套code,并测量(如果有的话),在速度上的差异

从实用的角度来看,调用清除()实际上不会降低内存(使用的名单,其中,T> 本身),因为它不收缩列表的能力,不仅消除它所包含的值。创建一个新的名单,其中,T> 将导致一个新的列表进行分配,这将反过来导致更多的分配与增长。然而,这并不意味着它会慢一些 - 在许多情况下,重新分配将是的更快的,你就不太可能推动大型阵列到更高垃圾收集代,这反过来又可以保持气相色谱过程要快得多。不知道您的具体方案和测量的在一个分析器,也没有办法知道这是在您的方案更好。

腾讯8分钟产品课第三集 需求

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>()?

解决方案

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.

The best option here would be to:

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).

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. 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.