由于关于使用List.FindIndex()而不是Linq查找索引的速度似乎存在一些争议,因此我编写了一个测试程序。
这假设您只关心查找列表中第一个匹配项的索引。它不处理多个匹配项。
另请注意,此测试是最坏的情况,因为匹配项位于列表的最后。
我的 x86 版本构建结果(在 Windows 8 x64,四核处理器上运行):
Calling Via FindIndex() 100 times took 00:00:00.9326057
Calling Via Linq 100 times took 00:00:04.0014677
Calling Via FindIndex() 100 times took 00:00:00.8994282
Calling Via Linq 100 times took 00:00:03.9179414
Calling Via FindIndex() 100 times took 00:00:00.8971618
Calling Via Linq 100 times took 00:00:03.9134804
Calling Via FindIndex() 100 times took 00:00:00.8963758
表明List.FindIndex() 比使用 Linq 快大约四倍。
这是测试代码:
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Demo
{
class Test
{
public string FilePath;
}
class Program
{
private void run()
{
int count = 1000000;
List<Test> list = new List<Test>(count);
for (int i = 0; i < count; ++i)
list.Add(new Test{ FilePath = i.ToString()});
string target = (count-1).ToString();
for (int trial = 0; trial < 4; ++trial)
{
Action viaFindIndex =
(
() =>
{
int index = list.FindIndex(x => (x != null) && (x.FilePath == target));
}
);
Action viaLinq =
(
() =>
{
int index = list.Select((x, i) => new { Item = x, Index = i })
.First(x => (x != null) && (x.Item.FilePath == target))
.Index;
}
);
viaFindIndex.TimeThis("Via FindIndex()", 100);
viaLinq.TimeThis("Via Linq", 100);
}
}
private static void Main()
{
new Program().run();
}
}
static class DemoUtil
{
public static void TimeThis(this Action action, string title, int count = 1)
{
var sw = Stopwatch.StartNew();
for (int i = 0; i < count; ++i)
action();
Console.WriteLine("Calling {0} {1} times took {2}", title, count, sw.Elapsed);
}
}
}
因此,鉴于List.FindIndex() 比使用 Linq 更快且更易于阅读,我认为没有理由使用 Linq 来解决这个特定问题。
int index = list.FindIndex(x => (x != null) && (x.FilePath == target));
对
int index = list.Select((x, i) => new { Item = x, Index = i })
.First(x => (x != null) && (x.Item.FilePath == target))
.Index;
第一个版本在 IMO 的所有方面都获胜。