#ifdef #ifndef in Java
Asked Answered
W

8

113

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

Winfrid answered 28/11, 2009 at 21:38 Comment(0)
S
131
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.

Stephie answered 28/11, 2009 at 21:50 Comment(8)
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.Winfrid
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.Tipple
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)Gath
@Gath : true, plus this doesn't allow you to do something like : private void foo(#ifdef DEBUG DebugClass obj #else ReleaseClass obj #endif )Pitiful
what about imports (for example, regarding to classpath)?Sonya
@Mark, Is this behavior guaranteed by the JLS?Naca
@tomwhipple, ternary operator, or static initialisation blocks, you would just have to split the definition and initialisation.Bollinger
Not the same! Code will be present when compiled, and can be de-compiled and even changed!Mythos
I
48

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
Impend answered 28/11, 2009 at 21:49 Comment(2)
Is this javac specific, or is this behavior actually guaranteed by the JLS?Naca
@pacerier, I have no idea if this is guaranteed by the JLS, but it's been true for every java compiler I've come across since the 90's, with the possible exception of prior to 1.1.7, and only because I didn't test it then.Normalize
W
12

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:

    boolean flag1 = true;
    boolean flag2 = false;
    int j=0;
    for(int i=0;i<1000000000;i++){
        if(flag1)
            if(flag2)
                j++;
            else
                j++;
        else
            if(flag2)
                j++;
            else
                j++;
    }

runs about 3 seconds on my computer.
And this one

    final boolean flag1 = true;
    final boolean flag2 = false;
    int j=0;
    for(int i=0;i<1000000000;i++){
        if(flag1)
            if(flag2)
                j++;
            else
                j++;
        else
            if(flag2)
                j++;
            else
                j++;
    }

runs about 1 second. The same time this code takes

    int j=0;
    for(int i=0;i<1000000000;i++){
        j++;
    }
Winfrid answered 28/11, 2009 at 22:16 Comment(3)
That is interesting. It sounds like JIT already supports conditional compilation! Does it work if those finals are in another class or another package?Vyatka
Great! Then I believe this must be a runtime optimization, the code is not actually being stripped at compile-time. That's fine as long as you use a mature VM.Vyatka
@joeytwiddle, Keyword is "as long as you use" a mature VM.Naca
M
2

Never used it, but this exists

JCPP is a complete, compliant, standalone, pure Java implementation of the C preprocessor. It is intended to be of use to people writing C-style compilers in Java using tools like sablecc, antlr, JLex, CUP and so forth. This project has has been used to successfully preprocess much of the source code of the GNU C library. As of version 1.2.5, it can also preprocess the Apple Objective C library.

http://www.anarres.org/projects/jcpp/

Michealmicheil answered 28/11, 2009 at 21:40 Comment(1)
I'm not sure this suits my need. My code is written in Java. Maybe you are proposing me to get their's sources and use them to preprocess my code?Winfrid
D
2

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 than if (LOG.isDebugEnabled()) { ... } stuff, not to mention being more concise at the same time.

If you use Maven, there is a similar feature described here.

Dougdougal answered 13/7, 2012 at 11:1 Comment(0)
B
2

If you use IntelliJ there is a plugin called Manifold, that - along with many other features - allows one to use #ifdef and #define in Java.

Plugin url: https://manifold.systems/

Preprocessor information: https://github.com/manifold-systems/manifold/tree/master/manifold-deps-parent/manifold-preprocessor

PS: I am not affiliated with them, we just happen to use it, and it helps a lot with out workflow (which is likely NOT typical for Java development)

Biflagellate answered 17/12, 2020 at 15:55 Comment(0)
V
1

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.

Villein answered 28/11, 2009 at 21:41 Comment(1)
The changes are very minor. Like testing some conditions to know in advance the requested result instead of recomputing it. So the overhead of call to the function could be not suitable for me.Winfrid
T
0
final static int appFlags = context.getApplicationInfo().flags;
final static boolean isDebug = (appFlags & ApplicationInfo.FLAG_DEBUGGABLE) != 0
Taliped answered 21/9, 2015 at 12:45 Comment(1)
What are context and getApplicationInfo?Jiggermast

© 2022 - 2024 — McMap. All rights reserved.