Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
333 views
in Technique[技术] by (71.8m points)

c# - is it better performance wise to use the concrete type rather than the interface

I have run into some rules (recommendations) to use concrete List and Dictionary rather than IList and IDictionary, given the sample tests that show accessing through the interface is quite a bit slower. For example, adding 10000 values to a list and then doing a Count on the list 1 billion 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).

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

The IList version is compiled to:

            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 
            }

The access to IList.Count is compiled into a call instruction.

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 
            }

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...