Friday, April 22, 2011

The value of a $

What really does happen when you type $ into your code?  I know it’s magic, but what really is going on?  I keep that in mind when doing anything with jQuery.  I always ask, is this the most efficient way to handle this task?  No matter how far I’ve progressed, looking at code I’ve written in the past always makes me shiver.  YOU SHOULD TOO!  Everyday is a learning experience; finding new techniques and trying them out will catapult you to new levels.
As I progress along finding the happy medium between jQuery and it’s parent: Javascript, I’m always looking for simple tweaks to optimize my code.  I’ve taken the time out to show a simple example of two different ways to populate a drop down.  Can you guess why the .append() method takes longer?

There’s a good reason why.  During the for loop, each option is being appended to the select.  That means I’m calling jQuery to work it’s magic EVERY time within this loop.  In this example, the code literally has to traverse the DOM 100 different times.  Even though each option is going to the same destination!  So, let’s look at it this way. 

If you had to walk across a fiery pit barefooted multiple times, would you carry as much as you possibly could each time or would you continually make that trip over and over again?  Personally, I’d run and not walk, but that’s just me…  Hopefully, that makes some sense.  Building an array full of the options and then traversing the DOM once, is infinitely more efficient.  I only make a call into jQuery once.  That’s an important distinction between these two techniques.  Traversing the DOM using jQuery is a slow task in some regards, especially in the example above.
Feel free to play around with the code sample provided and see if you can come up with some more techniques where this same logic can be applied.  It may just save you some time…

No comments: