Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#ifdef #ifndef in Java

I doubt if there is a way to make compile-time conditions in Java like #ifdef #ifndef in C++.

My problem is that have an algorithm written in Java, and I have different running time improves to that algorithm. So I want to measure how much time I save when each improve is used.

Right now I have a set of boolean variables that are used to decide during the running time which improve should be used and which not. But even testing those variables influences the total running time.

So I want to find out a way to decide during the compilation time which parts of the program should be compiled and used.

Does someone knows a way to do it in Java. Or maybe someone knows that there is no such way (it also would be useful).

like image 371
jutky Avatar asked Nov 28 '09 21:11

jutky


2 Answers

private static final boolean enableFast = false;  // ... if (enableFast) {   // This is removed at compile time } 

Conditionals like that shown above are evaluated at compile time. If instead you use this

private static final boolean enableFast = "true".equals(System.getProperty("fast")); 

Then any conditions dependent on enableFast will be evaluated by the JIT compiler. The overhead for this is negligible.

like image 184
Mark Thornton Avatar answered Sep 21 '22 16:09

Mark Thornton


javac will not output compiled code that is unreachable. Use a final variable set to a constant value for your #define and a normal if statement for the #ifdef.

You can use javap to prove that the unreachable code isn't included in the output class file. For example, consider the following code:

public class Test {    private static final boolean debug = false;     public static void main(String[] args)    {        if (debug)         {            System.out.println("debug was enabled");        }        else        {            System.out.println("debug was not enabled");        }    } } 

javap -c Test gives the following output, indicating that only one of the two paths was compiled in (and the if statement wasn't):

public static void main(java.lang.String[]);   Code:    0:   getstatic       #2; //Field java/lang/System.out:Ljava/io/PrintStream;    3:   ldc     #3; //String debug was not enabled    5:   invokevirtual   #4; //Method java/io/PrintStream.println:(Ljava/lang/String;)V    8:   return 
like image 34
Phil Ross Avatar answered Sep 22 '22 16:09

Phil Ross