views:

45

answers:

2

There is a lot of discussion about the lack of macros in some languages, and the inefficiencies that can arise. Perhaps the most common example is the guard before a log statement.

To what extent can current & future optimisation be relied upon to do the right thing and obviate the need for a macro. In this example and in general?

// shorter
log.debug("Foo: "+ bar);

// faster?
if(log.isDebug()){
    log.debug("Foo: "+ bar);
}

// best or unnecessary? 
LOG_DEBUG("Foo: "+bar)

A similar argument exists for stack allocation. For 'normal' programming, does the programmer need to have the option to be explicit about this kind of thing is a more automatic approach the way forward?

+1  A: 

As for logging, even if macros were included in Java, I would still use the

// preferred
if (log.isDebugEnabled()) {
    log.debug("Foo: "+ bar);
}

form, as any sane implementation will cache the isXxxEnabled() flag giving a very small penalty for leaving the logging in the compiled version. Checking the flag prevents having to build the String argument which saves a significant amount of work.

In my experience with logging via macros you always need the logging in a situation that is unexpected, and having to install another version to get your logging might not reproduce the problem...

If you really want macros in a language that does not define them, you can always run cpp (or M4) on the source to preprocess before calling the compiler.

As for stack allocation, garbage collected languages like Java take away that burden, for languages close to assembler you will need these details sometimes.

rsp
+2  A: 

To complete the logging example: most logging framework have a varargs parameter by now, so you can use

log.debug("Foo: {}", bar);

The varargs methods perform the isDebugEnabled() check before actually performing the statement. So you get both advantages at the same time.

For macros, i'm a bit sad that Java does not have macros. But just a bit. I would love to have them for compile-time information (What was the version of the compile class? What was the exact date and time when the class was built? On which machine was the class built, on which architecture, with which javac etc.). But I know that we would have to deal with a lot of crappy unreadable code if we would allow Java Preprocessors for code and business logic.

mhaller
For compile time information you can use the replace action in ant. File version numbers you can get expanding keywords inside a string to be expanded by your versino control system.
rsp