2

Is it faster to assign a long value to an int variable using a cast or is using a long variable faster?

Or it is a choice, between consuming more memory and processing more?

Here is an example test:

import java.time.Duration;
import java.time.Instant;

public class NanoTest {
    final int loop = 20000;

    public void testNoCasting() {
        long sum = 0;
        long time = System.currentTimeMillis();

        for (int i = 0; i < loop; i++) {
            sum += System.currentTimeMillis() - time;
        }

        System.out.println(sum);
    }

    public void testIntCasting() {
        int sum = 0;
        long time = System.currentTimeMillis();

        for (int i = 0; i < loop; i++) {
            sum += (int) (System.currentTimeMillis() - time);
        }

        System.out.println(sum);
    }

    public static void main(String[] args) {
        NanoTest nt = new NanoTest();

    Instant start = Instant.now();

        nt.testNoCasting(); // or nt.testIntCasting();

        Instant end = Instant.now();

        System.out.print("Duration: ");
        System.out.println(Duration.between(start, end).getNano());

    }
}
Marcus Becker
  • 352
  • 4
  • 11

1 Answers1

6

A typecast from long to int just ignores the leading 32 bit, so it should be more or less for free.

Long (=64 bit) operations are more expensive on 32 bit CPUs -- a 32 bit CPU will need two machine instructions to add two 64 bit numbers (other operations may take many more). On 64 bit CPUs, there shouldn't be a difference in terms of CPU time.

The (implicit) cast the other way around (from int to long) requires a "sign extension", which means the high bits are filled from the highest bit of the smaller type. So it may actually have a (small) cost, as it is not just ignoring the high bits, but needs to bring them into a well-defined state.

Stefan Haustein
  • 18,427
  • 3
  • 36
  • 51
  • This level of explanation that I wanted to have. Thanks. – Marcus Becker Mar 23 '15 at 18:44
  • 1
    a 32bit CPu certainly uses _much_ more instructions for 64bit operations - you're using the term incorrectly. Even the most trivial operations usually include several instructions, some even result in thousands of instructions (like hardware AES decryption / encryption) for one single operation. – specializt Mar 23 '15 at 18:45
  • You are right -- I was just talking about addition (because that's used in the example). I think a multiplication should take four, and then for more complex operations this adds up accordingly. I have updated the answer accordingly. – Stefan Haustein Mar 23 '15 at 19:08