Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Will using longs instead of ints benefit in 64bit java

In a 64 bit VM, will using longs instead of ints do any better in terms of performance given that longs are 64 bits in java and hence pulling and processing 64 bit word may be faster that pulling 32bit word in a 64 bit system. (I am expecting a lot of NOs but I was looking for a detailed explanation).

EDIT: I am implying that "pulling and processing 64 bit word may be faster that pulling 32bit word in a 64 bit system" because I am assuming that in a 64 bit system, pulling a 32 bit data would require you to first get the 64 bit word and then mask the top 32 bits.

like image 634
Suraj Chandran Avatar asked Aug 01 '11 19:08

Suraj Chandran


People also ask

Is long in Java 64-bit?

long: The long data type is a 64-bit two's complement integer. The signed long has a minimum value of -263 and a maximum value of 263-1.

When should I use long instead of int?

Definition of long type In Java, the type long is 64-bit signed integer type. The type long is used where the type int is not that large to hold the desired value. The range of long is –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807 which is quite large, to hold the larger values like big whole numbers.

Are ints 32 or 64-bit?

int is 32 bits in size. long , ptr , and off_t are all 64 bits (8 bytes) in size.

How much memory do ints take up?

Ints can be as small as 1 byte, using only 12.5% percent as much memory. Strings, on the other hand, can't be simplified but can be avoided.


1 Answers

Using long for int probably will slow you down in general.

You immediate concern is whether int on 64 bit CPU requires extra processing time. This is highly unlikely on a modern pipelined CPU. We can test this easily with a little program. The data it operates on should be small enough to fit in L1 cache, so that we are testing this specific concern. On my machine (64bit Intel Core2 Quad) there's basically no difference.

In a real app, most data can't reside in CPU caches. We must worry about loading data from main memory to cache which is relatively very slow and usually a bottleneck. Such loading works on the unit of "cache lines", which is 64 bytes or more, therefore loading a single long or int will take the same time.

However, using long will waste precious cache space, so cache misses will increase which are very expensive. Java's heap space is also stressed, so GC activity will increase.

We can demonstrate this by reading huge long[] and int[] arrays with the same number of elements. They are way bigger than caches can contain. The long version takes 65% more time on my machine. The test is bound by the throughput of memory->cache, and the long[] memory volume is 100% bigger. (why doesn't it take 100% more time is beyond me; obviously other factors are in play too)

like image 97
irreputable Avatar answered Nov 13 '22 11:11

irreputable