对于带有 If 语句的每个循环 - 性能
For Each Loop With If Statement - Performance
我有一个复杂的对象,我正在尝试遍历对象并添加到另一个列表。
但是由于我在循环中几乎没有 if 语句来检查内部对象是否为 null,因此迭代会花费很多时间。我也在循环浏览大约 70000 个项目。
下面是代码,
var Product = model; //complex object
Parallel.ForEach({model, product => {
if(product.Type != null)//type a
{ A = a.Loca;//do something }
if(product.Type != null)//type b
{ B = b.Loca;//do something }
if(product.Type != null)//type c
{ A = c.Loca;//do something }
dataAsset.Push(new assetItems(A, B, C));
}
});
我正在努力提高性能。
通过仅检查一次 product.Type != null 来提高性能。您不需要分别检查三次。即
Parallel.ForEach({model, product => {
if(product.Type != null)
{ a;//do something
b;//do something
c;//do something
}
dataAsset.Push(new assetItems(a, b, c));
}
通过使用 Elvis 运算符,我能够提高性能。
我有一个复杂的对象,我正在尝试遍历对象并添加到另一个列表。
但是由于我在循环中几乎没有 if 语句来检查内部对象是否为 null,因此迭代会花费很多时间。我也在循环浏览大约 70000 个项目。
下面是代码,
var Product = model; //complex object
Parallel.ForEach({model, product => {
if(product.Type != null)//type a
{ A = a.Loca;//do something }
if(product.Type != null)//type b
{ B = b.Loca;//do something }
if(product.Type != null)//type c
{ A = c.Loca;//do something }
dataAsset.Push(new assetItems(A, B, C));
}
});
我正在努力提高性能。
通过仅检查一次 product.Type != null 来提高性能。您不需要分别检查三次。即
Parallel.ForEach({model, product => {
if(product.Type != null)
{ a;//do something
b;//do something
c;//do something
}
dataAsset.Push(new assetItems(a, b, c));
}
通过使用 Elvis 运算符,我能够提高性能。