Hello,
I was wondering what you would recommend for maximum performance. Either use the pino-provided printf-style string injection (pino.info('user: %s logged-in', userId)) or should I opt for the new JS template literals (pino.info(`user: id logged-in`))?
Do you have any tests on performance?
Does it matter?
I appreciate the advice!
Technically, the interpolated string will be faster than the native template literal. This is because template literals are _always_ evaluated. For example:
if (isDebug) {
// Will not be interpreted unless `isDebug` is truthy
pino.info('%s', 'foo')
}
if (isDebug) {
// Will be evaluated regardless of truthiness of `isDebug`
pino.info(`${foo}`)
}
Personally, I prefer to keep the signature pino.info('message string', {optional: 'data object'}). Thus, I use native template literals and eat the negligible (for my uses) cost.
That's true but interpolated string is slower when executed verses template literal.
So if your logs are always on (e.g. you're not doing a debug check) then template literals will be faster than interpolation.
But then template literals won't stringify your object and inline it in the string ('%o') etc.
So if you want an overall "best practice" recommendation for logging: interpolation.
If you're only logging strings, and you're always logging and for some reason logging is your bottleneck (with pino this is extremely unlikely) then try a template string. This situation is unlikely, so: interpolation.
But also use a template string if you feel like it, it'll be pretty much fine either way unless you're in a very strangely constrained scenario.
Long story short: it depends on your situation.
Thank you both for the very informational feedback! I'm opting for the template literal approach since my logs will always be printed regardless of the environment.
Of course, in my case, the performance of the logger doesn't really matter at all, but I'm sure you can relate, that I like optimizing and especially like knowing what the best practices are.