如何优化此代码

use*_*618 6 c# performance

它有一个属性:字符串代码和其他10个.

公共代码是字符串列表(string [])汽车列表(Car [])filteredListOfCars是List.

for (int index = 0; index < cars.Length; index++)
{
    Car car = cars[index];
    if (commonCodes.Contains(car.Code))
    {
         filteredListOfCars.Add(car);
    }
}
Run Code Online (Sandbox Code Playgroud)

不幸的是,这片方法的时间太长了.

我有大约5万条记录

我怎样才能降低执行时间?

Jar*_*Par 20

最简单的优化是将commonCodes从a string[]转换为更快的查找结构,例如a Dictionary<string,object>或a,HashSet<string>如果您使用.Net 3.5或更高版本.这将减少此循环的大O复杂性,并且取决于commonCodes的大小应该使此循环执行得更快.


Aar*_*ght 16

Jared已经正确地指出你可以用a来优化它HashSet,但我还想指出整个方法是不必要的,浪费了输出列表的内存并使代码不那么清晰.

您可以将整个方法编写为:

var commonCodesLookup = new HashSet<int>(commonCodes);
var filteredCars = cars.Where(c => commonCodesLookup.Contains(c.Code));
Run Code Online (Sandbox Code Playgroud)

filteredCars过滤操作的执行将被推迟,因此如果它的消费者只想要前10个元素,即通过使用filteredCars.Take(10),那么这不需要构建整个列表(或任何列表).