32 vs. 64-bits

There is often a great debate about whether their program should be compiled as 32 or 64-bit. People often think a program will run better on their 64-bit OS if it is 64-bit instead of 32-bit, but that is often not the case. In this post I will discuss some of the advantages and bottlenecks in a 32-bit program versus a 64-bit program.

Many people does not understand what it means that their program is n-bits compiled. (Where n can be 8, 16, 32, 64, and so on) It basically means how much memory your program can allocate. In 32-bits, we can allocate 232 bytes. In the 32-bit world, all objects pointers has 32 zeros and ones. For each bit, there is two posibillities. As there are 32 possible combinations, therefore 232 bytes. In the 64-bit world it would be 264 bytes. We would have the following mathematical formula: 2bits = total memory available to allocate. 

Let's say our program is 32-bit. As each byte in our memory would have a memory address of 32-bits, every pointer (object reference for C# and VB coders) will have the size of 32-bits (4 bytes). If we compiled our program as 64-bit, each pointer would be twice as big. To understand this better, let's look at an example:

C#:

struct Node
{
    Node l;
    Node r;
    int data;
}

C++:

struct Node
{
	Node* l, *r;
	int data;
}

(Struct is the same in both languages)

For a binary tree with n nodes in a x-bit program, the total size of the tree would be as following:

size = n(2x+32)

In our 32-bit program, we have 2540 nodes. This tree has then the size of 2540*(2*32+32) = 243840 bits (30KB).
Let's say we wanted to compile our program as 64-bit:  2540*(2*64+32) = 406400 bits (50KB). A memory increase of 60%. 

This is the most common case for all program which moves from 32 to 64-bits, a memory increase of 60%. As we would get larger objects, memory fragmentation would also occur more frequent. 

A 64-bit CPU as a larger register than a 32-bit CPU. This leads to some loops would run faster as the CPU would not have to fetch data from the memory or cache (Code from Wikipedia):

int a, b, c, d, e;
for (a=0; a<100; a++)
{
  b = a;
  c = b;
  d = c;
  e = d;
}

 

To summarize, compiling a program as 64-bit often does not lead to any significant performance improvement. However, if your program depends on heavy calculation such as cryptography or video rendering, there could be a noticeable gain. Unless your program is a Twitter client, a normal GUI application that does not do much than displaying data from a file or the web, 32-bit may be the way to go. However, if you are writing a driver, database, image processing software, codecs or games, 64-bit would be the better choice. For mobile devices, 32-bit would be the best option as 64 would require more memory and would therefore require more juice from your battery. Most smartphones does not require much more than 2-3GB of ram and we are not there yet to switch over to 64-bit mobile OSes.