tags:

views:

228

answers:

2

In a logging system, every log output is done by a helper class with a method such as this one

public void debug(String message) {
    Logger logger = Logger.getLogger(getCallingClass());
    logger.debug(message);
}
...
public Class getCallingClass() {
/*
Calls Thread.getStackTrace() and back traces until the class on the stack trace 
!= this.getClass(). 
*/
    return classFound;
}

How expensive is this to run and could it have significant performance hits?

+4  A: 

Yes, there is some overhead to this call, but in all likelyhood, you're going to do something like this:

public static boolean DEBUG_ON = true; //change this before your production build

then,

public void debug(String message){
  if(DEBUG_ON){
     //stack code here
  }

}

Which will cause you to not take the hit in your real code.

Even then, for exceptions, you're going to throw a whole stack traced Exception in your production build.

Note that if you are using a decent logging subsystem, they will probably already do something based on the logging level (in our log system, depending on the level, debug() is basically a no-op). Log4j and others have different ways of handling this.

Lastly, I'd say: Don't worry about it until it proves to be a real performance problem. Premature Optimization is the root of all evil :)

Kylar
instead of using a boolean flag this condition could be used logger.isDebugEnabled()
daedlus
a better way is to use preprocessing directives.
Orentet
There's benefits to both. with the static final boolean, the compiler will just remove anything inside the if() statement, so it's kinda like a preprocessor directive ;)
Kylar
At any given time my (Windows) system is running about 50-80 programs, services and device drivers. If every one of them uses just 20% more resources (CPU and memory) than they would have if the programmer thought just a little about performance, that amounts to a huge hit in what my hardware can do. Thinking about performance **before** you write the code **is not** the root of all evil (the love of money is).
Software Monkey
A: 

From what I recall, there's some impact in using Thread.getStackTrace() - especially with large stacks (such as when using in server-side or J2EE situations). You could try Throwable.getStackTrace() for better performance.

At any rate, calling those functions regularly (as opposed to doing so in an exception situation) will impact your app.

Traveling Tech Guy
I doubt whether new `Throwable().getStackTrace()` is going to anything more than call `Thread.getStackTrace()` under the hood.
Software Monkey