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).
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.
This solution is better then mine. When I tried to initialize the variables with a presetted outer value the running time went back to 3 seconds. But when I defined the variables as static class variables (and not a function local variable) the running time returned to 1 second. Thanks for the help.
IIRC, this even worked before Java had a JIT compiler. The code was removed by
javac
I think. This only worked if the expression for (say)enableFast
was a compile time constant expression.Yes, but this conditional must reside within a method, correct? What about the case where we have a bunch of private static final Strings that we'd like to set. (e.g. a set of server URLs that are set differently for production vs. staging)
@tomwhipple : true, plus this doesn't allow you to do something like :
private void foo(#ifdef DEBUG DebugClass obj #else ReleaseClass obj #endif )
what about imports (for example, regarding to classpath)?