Click here to Skip to main content
15,881,852 members
Articles / Programming Languages / Javascript
Tip/Trick

Lazy Binding for Logging in JavaScript

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
29 Jan 2015CPOL 10.5K   5   2
How to wrap costly functions to execute them only when needed, especially for debugging purposes

Introduction

If you are still using alert() function to debug your JavaScript program, it's time to move on to using console.log() function so that log messages are only visible in Developer Tool.

Next, you need to know that the following line has a huge negative impact on your script's performance:

JavaScript
console.log( $('#div1').html() ); 

Why? Because the div1 could be a huge element on the page. So, you Googled and learned to create a Logger module which would suppress certain messages by a pre-configured log level, similar to:

JavaScript
Logger.debug("I'm a debug message!");
Logger.info("OMG! Check this window out!", window);
Logger.warn("Purple Alert! Purple Alert!");
Logger.error("HOLY SHI... no carrier.");

Source: https://github.com/duongchienthang/js-logger

With the new Logger module, you may think it would take away the cost of reading the DOM by doing:

JavaScript
Logger.setLevel(Logger.OFF);
Logger.debug( $('#div1').html() ); 

But you are wrong. The beast $('#div1').html() still runs as always and costs you performance unless you do the following:

JavaScript
Logger.debug( $().html.bind($('#div1')) );

I know it hurts your eyes if you are not familiar with the Function.prototype.bind() function. The $().html.bind() piece will return a wrapper function of the jQuery .html() function. That wrapper function will always be evaluated instead of the actual .html() function.

You can apply this trick to any functions that would potentially consume lots of memory and processing time, such as:

JavaScript
Logger.debug( JSON.stringify.bind(null, myVeryBigAndRecursiveJsObject) );

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
Questionfunction.bind usage... Pin
Nitij31-Jan-15 21:17
professionalNitij31-Jan-15 21:17 
AnswerRe: function.bind usage... Pin
Thang Believe1-Feb-15 1:31
Thang Believe1-Feb-15 1:31 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.