Print statements and debugger messages

I just noticed this feature of Rails. What’s wrong with this:

logger.debug "Person attributes hash: #{@person.attributes.inspect}"

In the above example, There will be a performance impact even if the allowed output level doesn’t include debug. The reason is that Ruby has to evaluate these strings, which includes instantiating the somewhat heavy String object and interpolating the variables, and which takes time. Therefore, it’s recommended to pass blocks to the logger methods, as these are only evaluated if the output level is the same or included in the allowed level (i.e. lazy loading). The same code rewritten would be:

logger.debug {"Person attributes hash: #{@person.attributes.inspect}"}

This is so AWESOME.

In the Java World, we always had to do something like this:

if logger.level <= Logger::DEBUG
  logger.debug "Person attributes hash: #{@person.attributes.inspect}"