Thread.getStackTrace()有多昂贵? [英] How Expensive is Thread.getStackTrace()?

查看:1740
本文介绍了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.

即便如此,对于异常,你将在生产版本中抛出整个堆栈跟踪的Exception。

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

请注意,如果您正在使用一个不错的日志记录子系统,他们可能已经根据日志记录级别做了一些事情(在我们的日志系统中,取决于级别,调试( )基本上是无操作)。 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆