Tuesday 2 August 2022

Constant folding in Java

Constant folding is a compiler optimization technique, where recognizing and evaluating constant expressions is done at compile time rather than computing them at runtime.

 

For example,

double d1 = (10 * 87.8654 * 123) - 98;

 

Java compiler evaluate the above constant expression while generating the byte code, and interpreted as ‘double d1 = 107976.442;’

 

ConstantFoldingDemo.java

public class ConstantFoldingDemo {

    private static void dummyCalc() {
        double d1 = (10 * 87.8654 * 123) - 98;
        double d2 = (11 * 88.8654 * 124) - 99;
        double d3 = (12 * 89.8654 * 125) - 100;

        System.out.println("d1 : " + d1);
        System.out.println("d2 : " + d2);
        System.out.println("d3 : " + d3);
    }

    public static void main(String[] args) {
        dummyCalc();
    }

}

 

In the above snippet, values of d1, d2 and d3 are evaluated at compile time. To confirm the same, I decompiled the ConstantFoldingDemo.class file, you can observe the findings in following image.



You may like

Interview Questions

How to check two float values equality?

How to check whether a class is loaded or not in Java?

How to get a random element from Set?

Extract the elements of specific type in a collection

Method overloading ambiguity with null values in Java

Quick guide to load balancers

No comments:

Post a Comment