"tl;dr" included
When trying to disable Logging so as to avoid spam once deploying, I used to do something like
if (isDebug)
console.log(...);
but I felt like (or read online) this would slow the code overall because the condition would be evaluated each time (and I usually include a lot of these, and the functions are called often, either via loops, setIntervals or w/e).
As such, I now switched to simply "emptying" the functions using a custom logger like
function LOGGER_MODULE_FACTORY() {
let current_log_level = "log";
return {
log: console.log,
info: console.info,
warn: console.warn,
error: console.error,
setDebug: function(logLevel) {
current_log_level = logLevel;
this.log = (logLevel === true || logLevel === "log") ? console.log : function () {};
this.info = (logLevel === true || logLevel === "log" || logLevel === "info") ? console.info : function () {};
this.warn = (logLevel === true || logLevel === "log" || logLevel === "info" || logLevel === "warn") ? console.warn : function () {};
this.error = (!logLevel) ? function () {} : console.error;
return logLevel;
},
getCurrent_log_level: function () { return current_log_level; }
}
}
Thinking that it would probably be quicker to run an empty function than evaluating an expression and it felt cleaner to write.
I tried creating a fiddle to test my theory and compare performance but the values are often pretty random...
My reasoning relied on the fact that I read few things about CPUs and, apparently, they do things on their own in order to optimize the general run-time like, for instance, skipping useless operations: Say we have :
a = x
b = y
c = a + 3
The CPU would actually ignore the second line (or something... I am far from being an expert ahah, I just curiously read that fact).
Now, since we, on our browser, may access any globally declared variable at some point using the console, this cannot happen and so I felt I should simply ask online :
tl;dr:
Is calling an empty/bodiless function repeatedly (the pages I create basically run 24/7 on a dashboard) better, performance-wise than placing a condition in front of the original function (console.log / info / warn / error) ?
Aucun commentaire:
Enregistrer un commentaire