Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compiling without assertions

I know assertions can be enabled/disabled at runtime for debugging and production, respectively. However I found that assertions also increase the size of the generated binary (about 100-200 bytes in the example below).

In C and C++, we can do this at compile time by having #define NDEBUG before #include <assert.h>.

Is there any way for the Java compiler to automatically do this? I'd like to leave them in the source code for debugging purposes later on. But I also don't want the resultant binary to be any larger than necessary (we have a size limit as design requirement).

C code:

//#define NDEBUG
#include <assert.h>

int main(void) {
    assert(0); // +200 bytes without NDEBUG, 0 with NDEBUG
    return 0;
}

Java code:

public class Test {
    public static void main(String[] args) {
        assert(System.nanoTime()==0); // increases binary size by about 200 bytes
    }
}

In response to bn.'s answer:

public class Test2 {
    public static final boolean assertions = false;

    public static void main(String[] args) {
        if(assertions) {
            assert(System.nanoTime()==0);
        }
    }
}

EDIT: In fact, it seems to me that this enabling/disabling is a more useful compile-time feature than run-time. I mean, how many end users will enable them? As far as a programmer is concerned during the debug process, he/she will likely be recompiling code anyways.

like image 363
tskuzzy Avatar asked Jun 06 '12 15:06

tskuzzy


1 Answers

This is not possible as a built in compilation step. You can however, do this by adding conditional blocks around your assertions.

See the article "Removing all Trace of Assertions from Class Files" for more information.

like image 112
bn. Avatar answered Oct 04 '22 17:10

bn.