views:

860

answers:

7

I am porting an existing application to C# and want to improve performance wherever possible. Many existing loop counters and array references are defined as System.UInt32, instead of the Int32 I would have used.

Is there any significant performance difference for using UInt32 vs Int32?

A: 

I would look at the ILASM output of whatever code you are interested in.

kenny
A: 

Its going to allocate the same amount of memory either way (although the one can store a larger value, as its not saving space for the sign). So I doubt you'll see a 'performance' difference, unless you use large values / negative values that will cause one option or the other to explode.

GWLlosa
They both store the same range, it's just that half of the signed integer's range is negative.
GalacticCowboy
It's more accurate to say that they store the same number of values, as their range is clearly different.
Hosam Aly
+6  A: 

I don't think there are any performance considerations, other than possible difference between signed and unsigned arithmetic at the processor level but at that point I think the differences are moot.

The bigger difference is in the CLS compliance as the unsigned types are not CLS compliant as not all languages support them.

Scott Dorman
+1  A: 

I haven't done any research on the matter in .NET, but in the olden days of Win32/C++, if you wanted to cast a "signed int" to a "signed long", the cpu had to run an op to extend the sign. To cast an "unsigned int" to an "unsigned long", it just had stuff zero in the upper bytes. Savings was on the order of a couple of clock cycles (i.e., you'd have to do it billions of times to have an even perceivable difference)

James Curran
+2  A: 

There is no difference, performance wise. Simple integer calculations are well known and modern cpu's are highly optimized to perform them quickly.

Alan
+1  A: 

Hi there, this isn't really to do with performance rather requirements for the loop counter.

Prehaps there were lots of iterations to complete

        Console.WriteLine(Int32.MaxValue);      // Max interation 2147483647
        Console.WriteLine(UInt32.MaxValue);     // Max interation 4294967295

The unsigned int may be there for a reason.

Rohan West
+1  A: 

These types of optimizations are rarely worth the effort. Use the data type that is most appropriate for the task and leave it at that. If this thing so much as touches a database you could probably find a dozen tweaks in the DB design, query syntax or indexing strategy that would offset a code optimization in C# by a few hundred orders of magnitude.

JohnFx