[英]Fastest way to set properties to null in C# 4
What is the fastest way to set properties (any one) to null
in an IEnumerable
? 在
IEnumerable
中将属性(任何一个)设置为null
的最快方法是什么? Is foreach
my only option? 是
foreach
我唯一的选择?
If you have a very large list, you could consider doing this in parallel: 如果列表很大,则可以考虑并行执行此操作:
enumerable.AsParallel().ForAll(a => a.Value = null);
But worth benchmarking and baring in mind that your objects will now need to be threadsafe. 但是值得进行基准测试和修改,因为您的对象现在需要是线程安全的。
Quick tests here showed a return on investment when the list size was above 10 million items*. 此处的快速测试显示,当列表大小超过1000万个*时,投资回报率*。 Lower list sizes and the costs of setting up the parallel processing outweighs the benefits.
较小的列表大小和设置并行处理的成本超过了好处。
*Your Mileage Will Vary *您的里程会有所不同
There are two ways of achieving your goal: 有两种实现目标的方法:
As you mentioned: 如您所述:
foreach(var item in enumeration) { item.Property = null; }
You can go with LINQ also: 您还可以使用LINQ:
enumeration.ToList().ForEach(item => item.Property = null);
While the second way looks a shorter and better readable, it may execute slower, because as Jeppe Stig Nielsen pointed out, the IEnumerable
gets converted into a List
(be enumerating it the first time) and that list gets enumerated again, to finally set the property. 虽然第二种方法看起来更短且可读性更好,但执行起来可能会变慢,因为正如Jeppe Stig Nielsen指出的那样,
IEnumerable
会转换为List
(第一次枚举),然后再次枚举该列表,以最终设置属性。
Thus you are right: foreach
is your only option. 因此,您是对的:
foreach
是您唯一的选择。 However the foreach
-representation will look like, you always will need to iterate over the collection to modify each item. 但是,
foreach
-representation看起来像,您总是需要遍历集合以修改每个项目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.