I have done a bit of research and most of what I find is a good few years old. I’m new to JS and I’m building up my knowledge gradually.
Console.log() is an incredibly helpful tool, however I’m incredibly wary of its generally poor performance (https://jsperf.com/console-log1337/16 or https://jsperf.com/console-log1337/33 as a basic example), as well as bad reputation.
In the event I need to leave console.log() style error messages in a production application/website, is there a more performant alternative that is native to vanilla JS (no frameworks/libraries)?
My initial thought was to instead push all log items into an array which could later be collected (if required) however it seems that doesn’t work in conjunction with Promise.all() very well - rather than getting say, 10 items in an array, I instead get back either a single array with the last value, or 10 separate arrays.
Is there a native or most recommended alternative (appreciate this is open to “opinion” - I’m not sure how else to word it!)?
Ps - apologies for lack of formatting... mobile!
... poor performance
One of the testcases compares calling an empty function to calling console.log
. An empty function will probably be inlined by the JIT compiler, so you are actually comparing no code at all to console.log
. For sure no code at all is way faster.
I never experienced any (noticible) lag due to logging, except you are logging inside a render loop or anything executed very, very often.
... bad reputation
Seriously? In my eyes JS has great ways to debug compared to other languages (probably because JS got the nicest bugs :)) as you can view nested structures "live", you can halt execution at breakpoints, you can prepare code for debugging with the debugger;
statement, you can dump the whole memory, visualize GC behaviour, hot functions and much more. Yes, all those features lower performance, however the console performs quite well.
is there a more performant alternative that is native to vanilla JS (no frameworks/libraries)?
The logging is directly written into the engine executing JavaScript, that means it can access a lot of things that you cannot access through JS, also native code will always be faster than compiled JavaScript (or equally fast, but no one can guarantee that).
In the event I need to leave console.log() style error messages in a production application/website ...
And who should read this logs? Do you want to ask your client to look into the console in the case of an error?
Logging in Production should not log everything you use through debugging, but just enough that you can track down errors, so some breadcrumbs to find out where the error occured (e.g. "menu open"), and the errors themselves.
If you don't want to write production logging by yourself, have a look at sentry for JS