Warm tip: This article is reproduced from serverfault.com, please click

#ifdef #ifndef in Java

发布于 2009-11-28 21:38:27

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

Questioner
jutky
Viewed
0
13.7k 2013-11-08 15:51:34
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.