msnews.microsoft.com wrote:
Thanks for the response. I hadn't considered negative values for x/y only
because that should never be the case in my app. It does makes sense though
when you consider that they could be negative. As far as speed goes, I also
expect the bit shift to be a tiny bit faster...but as you said, it shouldn't
really be enough to matter.
Thanks!
now I'm off to figure out where to change my usename in OE :)
"Jon Skeet [C# MVP]" <sk***@pobox.com> wrote in message
news:MP************************@msnews.microsoft.c om...
msnews.microsoft.com <st********@yahoo.com> wrote:
Two simple questions:
1) Shouldn't the code snippets below produce the same IL?
No - they might give different results if x or y are negative, for one
thing.
2) Which will be faster?
I'd expect the shift to be faster, but the obvious course of action is
to try it. However, unless this code is in the bottleneck of your app,
the chances are very slim that it'll make any significant difference.
Write it in the form you find most readable.
--
Jon Skeet - <sk***@pobox.com>
http://www.pobox.com/~skeet
If replying to the group, please do not mail me too
I'd just like to add - the difference is not in the division itself, but
in the compensation for the shift of negative numbers Jon mentioned.
This is the output of the JIT:
Shift version: Divide version:
00000000 push ebp 00000000 push ebp
00000001 mov ebp,esp 00000001 mov ebp,esp
00000003 sub esp,8 00000003 sub esp,8
00000006 push edi 00000006 push edi
00000007 push esi 00000007 push esi
00000008 mov edi,ecx 00000008 mov edi,ecx
0000000a mov esi,edx 0000000a mov esi,edx
0000000c mov eax,esi 0000000c mov ecx,esi
0000000e test ecx,ecx
00000010 jns 00000015
00000012 add ecx,0Fh
0000000e sar eax,4 00000015 sar ecx,4
00000011 imul eax,eax,13h 00000018 imul ecx,ecx,13h
00000014 mov edx,edi 0000001b mov eax,edi
0000001d test eax,eax
0000001f jns 00000024
00000021 add eax,0Fh
00000016 sar edx,4 00000024 sar eax,4
00000019 lea eax,[eax+edx+1] 00000027 lea eax,[ecx+eax+1]
0000001d pop esi 0000002b pop esi
0000001e pop edi 0000002c pop edi
0000001f mov esp,ebp 0000002d mov esp,ebp
00000021 pop ebp 0000002f pop ebp
00000022 ret 00000030 ret
Once you change the parameters to uint, the compiled funcitons become
almost equal, except for register usage, which should not affect
performance on todays processors ;)
HTH,
Stefan