Thread.getStackTrace() 有多贵? [英] How Expensive is Thread.getStackTrace()?
问题描述
在日志系统中,每个日志输出都是由一个辅助类完成的,其中的方法是这样的
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?
推荐答案
是的,这个调用有一些开销,但很可能,你会做这样的事情:
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
那么,
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.
请注意,如果您使用的是不错的日志子系统,它们可能已经根据日志级别执行某些操作(在我们的日志系统中,根据级别,debug() 基本上是无操作的).Log4j 和其他人有不同的处理方式.
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 :)
这篇关于Thread.getStackTrace() 有多贵?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!