The past few years
Refactoring the bone yard
The web application that I started creating nearly 5 years ago that I am still fully supporting (Project Name: Droid Track, aka: Location Over Time, aka: Display Tracks) is a large pit of spaghetti’d out jQuery code. The algorithms and logical workflow that I have in place are actually something to brag about, but the entire app needed a performance assessment and facelift.
Changing $(this) to this: $(this) is actually an extra function call, so if you feel it is more convenient, it is better to at least cache it in a variable, but I got rid of them entirely; over 100 instances. Instead, using ‘this’, the native functionality to grab an instance of an object.
Concerning $(this) & this scoped variablesvar $thisVal = $(this).val(), thisVal = this.value; var $isChecked = $(this).prop(‘checked’)), var isChecked = this.checked;
If you are familiar with jsperf, you would know these native functions all run 90%+ faster than any jQuery, and after this refactor, it was obvious.
Created helper functions that mimic jQuery’s/Sizzle’s selector engine: I created utility functions that take in an element from the DOM, and return a blank string rather than null or undefined so that I can select elements without needing to know the status of their existence (since some elements will only be on the page for select user types). This looks something like:
I had each of them run side by side multiple times in a cache-less browser and ran several profiles. On average, the entire application would load in 8-9 seconds before the refactor. After the changes, it will now run in 5-6 seconds, a huge, noticeable change for this rather large application. And it wasn’t just the areas that I explicitly changed that felt faster, the entire application was snappier because of the smaller memory footprint.
This was one of the biggest refactors I had done to any of my personal projects, and I must say, my satisfaction level was (still is) through the roof!
This was not only a great change for my application, but for my growth in understanding front end programming. In this time, I was able to fully investigate how jQuery works on a function level, and weed out any functions that were causing too much overhead.
I always ask, ‘What would Google do?’, and aside from one site (their slowest, ill-performant site under their name http://blog.jquery.com/2007/11/02/google-using-jquery/), they don’t use heavy frameworks, they do it the best way. That is why you always find yourself pleased with Google’s plethora of websites.