List T.IndexOf()与List T.FindIndex()的效率

编程入门 行业动态 更新时间:2024-10-28 20:18:52
本文介绍了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()的效率

本文发布于:2023-11-08 16:37:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1569903.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:效率   List   IndexOf   FindIndex

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!