Question

If I understand it right an int-variable is saving in 32 bit, restricting it to -2 billion to 2 billion something. However if I use a long-variable it will save in 64 bit allowing a lot more numbers to be stored. I'm sitting on a 64 bit system, but will my code run well on a 32 bit system if I store data in 64 bit?

Thank you!

Was it helpful?

Solution

Don't you worry about that. The long value will be stored in 2 memory addresses. Int64/long will always be 64bit, and Int32/int will always be 32bit.

There are a few implications (concerning memory space and performance), but the most noticeable may be that write/read operations won't be atomic on 32bit systems, but you shouldn't expect them to be atomic anyway, since the c# specification makes no such guarantee.

Either way, the point is: this is not something you should ever worry about - the CLR abstracts these things away. Use whichever type suits you best.

OTHER TIPS

On a 32 bit system, operations on a 32 bit integer can be performed in a single machine register. But operations on a 64 bit integer require two machine registers, and are quite a bit less efficient than 32 bit operations. And of course, being twice the size, long uses more memory than int. If you have arrays of these types then you will consume your cache twice as fast if you use long. That can also have performance implications.

So, if you can use int, you should prefer it to long. However, if the 32 bits of range afforded by int are not sufficient for the correctness of your program, you would need to use long.

Of course, even though operations on 64 bit integers, are less efficient when executed on a 32 bit machine, only profiling would tell you whether or not it actually matters.

Perhaps the bottom line is that programmers should not be wilfully profligate. Why use 64 bits, if 32 bits suffice?

Yes. The data type is supported on both. But the 64 bit integer isn't native to 32 bit processors. If you use a 64 bit type, and you compile for 64 bit only (you can choose x64 or x86 (=32bit) as a targer), then the compiler might use specific 64 bit instructions, making your application run a bit faster. Theoretically, that is, in practice you will probably not notice this.

The tradeoff is that that application will not run on a 32 bit platform. The other way around will work. So if you plan to target both platforms, you need to either compile to 32 bit only, or compile two times, once for each platform.

For the availability of the long type it doesn't matter. You can always use it.

You can try yourself like this:

Console.WriteLine(sizeof(long));

Then compile it as x86 instead of AnyCPU and run it. You can run 32 bit programs on 64 bit Windows as well - see what the result is.

There are even larger number types such as BigInteger and they also work on 32 and 64 bit operating systems.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top