它是更好的性能明智的做法是使用具体类型而不是接口 [英] is it better performance wise to use the concrete type rather than the interface

查看:172
本文介绍了它是更好的性能明智的做法是使用具体类型而不是接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一些规则(推荐)为用具体的列表和字典,而不是IList的和IDictionary的给予,显示通过该接口也相当慢一点访问抽样检验。例如,添加10000值的列表,然后做就行了10亿次的计数表明通过接口做,就慢28倍,然后通过具体类这样做。即,通过具体的类需要80毫秒,通过该接口需要2800ms这表明它是通过接口到底有多慢。鉴于此会是合理的使用具体类。还有一个原因,为什么界面是如此的慢得多(可能更直指有人谁知道更多有关.NET的内部)。

I have run into some rules(recomendations) to use concrete List and Dictionary rather than IList and IDictionary given the sample tests that show accessing through the interface it quite a bit slower. For example , adding 10000 values to a list and then doing a count on the list 1billion times shows that doing it through an interface is 28 times slower then doing it through the concrete class. ie, through the concrete class it takes 80ms, through the interface it takes 2800ms which shows how really slow it is through the interface . Given this would it be reasonable use the concrete class. Is there a reason why the interface is so much slower(probably more directed at someone who know more about the internals of .net).

谢谢 斯科特

推荐答案

我认为这是很明显的,如果你看一下拆解:

I think it's quite obvious if you look at the disassembly:

的IList 版本编译:

            for (int i = 0; i < 1000000000; i++) 
0000003d  xor         edi,edi 
            { 
                count = lst.Count; 
0000003f  mov         ecx,esi 
00000041  call        dword ptr ds:[00280024h] 
00000047  mov         ebx,eax 
            for (int i = 0; i < 1000000000; i++) 
00000049  inc         edi 
0000004a  cmp         edi,3B9ACA00h 
00000050  jl          0000003F 
            }

IList.Count 被编译成通话指令。

列表的版本,另一方面是内联

The List version on the other hand is inlined:

            for (int i = 0; i < 1000000000; i++) 
0000003a  xor         edx,edx 
0000003c  mov         eax,dword ptr [esi+0Ch] 
0000003f  mov         esi,eax 
00000041  inc         edx 
00000042  cmp         edx,3B9ACA00h 
00000048  jl          0000003F 
            }

在这里没有通话指令。只是一个MOV,INC,CMP和循环JL指令。当然,这是更快的。

No call instruction here. Just a mov, inc, cmp and jl instruction in the loop. Of course this is faster.

但要记住:通常情况下,你的执行的东西与你的列表的内容,你不只是进行迭代。这通常需要比一个函数调用更长的时间,因此调用接口的方法很少会导致性能问题。

But remember: Usually, you're doing something with the contents of your list, you're not just iterating over it. This will usually take much longer than a single function call, so calling interface methods will rarely cause any performance problems.

这篇关于它是更好的性能明智的做法是使用具体类型而不是接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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