List T.IndexOf()与List T.FindIndex()的效率 [英] Efficiency of List<T>.IndexOf() versus List<T>.FindIndex()

查看:467
本文介绍了List T.IndexOf()与List T.FindIndex()的效率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

其中一种方法

  • List<T>.IndexOf()
  • List<T>.FindIndex()
  • List<T>.IndexOf() and
  • List<T>.FindIndex()

在处理时间方面更有效吗?

is more efficient in terms of processing time?

在这种情况下,T的类型为String.

The type of T in this instance is String.

推荐答案

IndexOf使用要搜索的对象的Equals实现来执行for循环. FindIndex也会执行for循环,但会评估Predicate来检查是否匹配.

IndexOf performs a for-loop, using the Equals implementation of the objects being searched to look for a match. FindIndex also peforms a for-loop but evaluates a Predicate to check for a match instead.

他们每个人都归结为一个循环.性能上的差异(如果有的话)可以忽略不计.以下是一些MSDN摘录:

They each boil down to a for-loop. The difference in performance, if any, will be negligible. Here are some MSDN excerpts:

List<T>.IndexOf Method (T) :

此方法执行线性搜索;因此,此方法是O( n )操作,其中 n Count.

This method performs a linear search; therefore, this method is an O(n) operation, where n is Count.

List<T>.FindIndex Method (Predicate<T>) :

此方法执行线性搜索;因此,此方法是O( n )操作,其中 n Count.

This method performs a linear search; therefore, this method is an O(n) operation, where n is Count.

也就是说,这两个函数的用法有很大不同.前者假定您有一个来自列表的对象,而您只需要知道该对象在列表中的索引位置(如果有).

That said, the two functions would be used quite differently. The former assumes you have an object from the list, and you just need to know at what index it exists at (if any) in the list.

后者假设您了解某个对象的某些条件,并且您想找到列表中对象与该条件匹配的第一个索引.可能有多个匹配项,但是该方法返回第一个匹配项.

The latter assumes you know some criteria about an object, and you want to find the first index where an object in the list matches that criteria. There could be multiple matches, but the method returns the first match.

这篇关于List T.IndexOf()与List T.FindIndex()的效率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆