【发布时间】:2018-03-30 21:53:04
【问题描述】:
我在 for 循环中对 SequenceEqual 和元素比较进行了比较。
static void Main(string[] args)
{
//var myList = new List<short>();
//var anotherList = new List<short>();
var myList = new short[2000000];
var anotherList = new short[2000000];
for (int i = 0; i < 2000000; i++)
{
//myList.Add(5);
//anotherList.Add(5);
myList[i] = 5;
anotherList[i] = 5;
}
var watch = System.Diagnostics.Stopwatch.StartNew();
//for (int i = 0; i < 2000000; i++)
//{
// if (myList[i] != anotherList[i])
// break;
//}
bool isEqual = myList.SequenceEqual(anotherList);
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Console.WriteLine(elapsedMs);
Console.Read();
}
当myList和anotherList为数组时,直接比较执行4ms,SequenceEqual执行21ms。当 myList 和 anotherList 为列表时,直接比较执行 13 ms,SequenceEqual 执行 30 ms。
如果它慢得多,是否有使用它有益的情况?我只能想到一个,它节省了几行代码。
【问题讨论】:
-
它对类型使用默认的相等比较器,这不一定与您使用 == 得到的相同
-
@Crowcoder 我可以尝试使用 Equals,但我怀疑会有很大的不同。
-
好吧,如果您在性能关键的应用程序中比较具有 200 万个项目的数组(碰巧也相等,这是最坏的情况),那么请确保您不应该使用
SequenceEquals。但在大多数其他实际应用程序中,它们之间的性能差异并不重要,而“节省几行”则是。 -
但它将是身份转换(我的意思是像'source as T[]'之类的东西),所以应该很快,因为没有执行任何转换。
-
我做了更多的测试。减速的很大一部分似乎在于
SequenceEqual将Lists 视为IEnumerable并不得不使用通用Enumerator。使用List特定的Enumerator可以使速度翻倍。
标签: c# performance linq ienumerable