Search code examples
javaperformanceprimitive

Java: Does primitive type casts performance impact?


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());

    }
}

Solution

  • 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.