C# For Loop、While Loop、LastIndexOf、IndexOf,为什么最后两个更快?
我在 C# 中使用 For 循环和 While 循环对 ArrayList 进行比较搜索进行了一些性能测试。
它似乎有二次方的时间消耗。
但是,如果我使用 LastIndexOf
或 IndexOf
来搜索列表,它会获得“比预期更快”的速度。
有谁知道原因吗?
I have done some performance testing in C# on using the For Loop and the While Loop for an ArrayList to do comparison search.
It seems to be having quadratic time consumption.
However, if I use LastIndexOf
or IndexOf
to search through the list, it gains "faster than anticipated" speed.
Does anyone know the reason?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我不懂 C#,但我可以提出可能的答案。
任何编程语言方法通常都是利用它们运行的处理器提供的快捷方式编写的,而您自己编写的代码则不会(例如,您必须声明必须保留在堆栈上的局部变量,需要较慢的查找时间,而不仅仅是一个临时寄存器变量)。因此,该语言本身执行的任何操作通常都会比您自己的代码更快。
I don't know any C# and yet I can put forward the likely answer.
Any programming language method are generally written in ways that take advantage of shortcuts made available by the processor that they run on - which your own written code will not (eg you'll have to declare local variables which will have to be kept on the stack, requiring slower lookup times, instead of just being a temporary register variable). Thus anything the language does natively will generally be quicker than your own code.
使用 ILSpy 并查看 LastIndexOf/IndexOf 方法的内部结构。这就是为什么它们更快的答案。
我有一种预感,List 内部使用 B 树或其他树,它具有 log(n) 的查找。您使用 for/foreach 所做的是执行线性查找,但需要一些额外的开销。如果您还记得数学课,那么您就会知道 log(n) 比线性线更平坦,因此查找速度更快......
Use ILSpy and take a look at the internals of LastIndexOf/IndexOf methods. There lies your answer as to why they are faster.
I have a hunch that the List internally uses a B-tree or some other tree, which has a lookup of log(n). What you are doing with for/foreach is performing a linear lookup with some extra overhead. If you remember your maths class then you'd know that log(n) is flatter than a linear line, thus having faster lookup...