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).
I think that I've found the solution, It's much simpler.
If I define the boolean variables with "final" modifier Java compiler itself solves the problem. Because it knows in advance what would be the result of testing this condition. For example this code:
runs about 3 seconds on my computer.
And this one
runs about 1 second. The same time this code takes
Conditionals like that shown above are evaluated at compile time. If instead you use this
Then any conditions dependent on enableFast will be evaluated by the JIT compiler. The overhead for this is negligible.
If you really need conditional compilation and you use Ant, you might be able to filter your code and do a search-and-replace in it.
For example: http://weblogs.java.net/blog/schaefa/archive/2005/01/how_to_do_condi.html
In the same manner you can, for example, write a filter to replace
LOG.debug(...);
with/*LOG.debug(...);*/
. This would still execute faster thanif (LOG.isDebugEnabled()) { ... }
stuff, not to mention being more concise at the same time.If you use Maven, there is a similar feature described here.
Use the Factory Pattern to switch between implementations of a class?
The object creation time can't be a concern now could it? When averaged over a long running time period, the biggest component of time spent should be in the main algorithm now wouldn't it?
Strictly speaking, you don't really need a preprocessor to do what you seek to achieve. There are most probably other ways of meeting your requirement than the one I have proposed of course.
javac will not output compiled code that is unreachable. Use a final variable set to a constant value for your
#define
and a normalif
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:
javap -c Test
gives the following output, indicating that only one of the two paths was compiled in (and the if statement wasn't):