[infinispan-dev] trace vs log.isTraceEnabled

Manik Surtani manik at jboss.org
Wed Dec 7 05:42:47 EST 2011


Bringing this thread up again, is it really true to say that 

   if (trace) log.trace("blah")

is as cheap as 

  log.trace("blah")

?

In the former, with tracing disabled, nothing happens after the condition check.  In the latter, you still construct a String "blah", and even if there is no complex interpolation or message construction, the basic String message is still constructed (and starts to take up PermGen space too, as literals are interned [1]).

So the case for the if (trace) pattern still stands IMO.

Cheers
Manik

[1] http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/String.html#intern() 
"All literal strings and string-valued constant expressions are interned."

On 28 Sep 2011, at 17:41, David M. Lloyd wrote:

> On 09/28/2011 11:35 AM, Mircea Markus wrote:
>> Hi,
>> 
>> I'm not aware of any convention on using trace vs log.isTraceEnabled() to guard the trace statements.
>> 
>> if (trace) log.trace("some request related stuff")
>> vs
>> if (log.isTraceEnabled()) log.trace("some request related stuff");
>> 
>> The former is more efficient, but cannot be managed at runtime. It seems to be the preferred form, so shall we stick with it?
> 
> If you're using the jboss-logging API, and your log statement does not 
> do any interpolation, then it is just as fast to do any of the following 
> (with no if):
> 
>    log.trace("blah");
>    log.tracef("the %s happened to %s", foo, bar);
>    log.tracev("the {0} happened to {1}", foo, bar);
> 
> In the case where trace logging is disabled, these are exactly as 
> efficient as the if (log.isTraceEnabled()) variants.  In the case where 
> it is enabled, it is marginally more efficient (though the trace log 
> itself is substantially more expensive of course).
> 
> Overall I'd avoid the "if" forms unless you're doing complex interpolation:
> 
>    log.trace("Foo " + bar + " baz " + zap);
>    log.tracef("the %s happened to %s", fooMethod().barMethod(), bar);
> 
> ...both of which incur the expense of the expression resolution even if 
> the log message is ultimately discarded.
> -- 
> - DML
> _______________________________________________
> infinispan-dev mailing list
> infinispan-dev at lists.jboss.org
> https://lists.jboss.org/mailman/listinfo/infinispan-dev

--
Manik Surtani
manik at jboss.org
twitter.com/maniksurtani

Lead, Infinispan
http://www.infinispan.org






More information about the infinispan-dev mailing list