Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 783
user455095 Avatar asked Nov 23 '10 14:11

user455095


1 Answers

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.

like image 130
Niki Avatar answered Oct 11 '22 06:10

Niki