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?
It looks like getting the current thread (and its associated ID) is not expensive, but getting the current thread and its stack trace is. The new throwable().getStackTrace() pattern seems to be a lot faster than the thread's stack trace pattern.
Also, note: this benchmark has almost no stack depth since its just a main method, so in a server environment this penalty will be a lot heavier.
Benchmark results:
Simple loop took 2 ms
Getting current thread took 10 ms
Getting stack trace took 29564 ms
Getting throwable stack trace took 19910 ms
Code:
Now with JDK 9 & 10, you can use StalkWalker, which is not an expensive call.
Yes, there is some overhead to this call, but in all likelyhood, you're going to do something like this:
then,
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 :)
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 tryThrowable.getStackTrace()
for better performance.At any rate, calling those functions regularly (as opposed to doing so in an exception situation) will impact your app.