I was working on a basic reverse mortgage calculator (input monthly payment, it returns how much you can afford). Not being a math wiz, I didn't spend too much time figuring out how to solve an equation that involves multiple variables, as well as some that are repeated.

Instead, I opted for a brute force approach, running through hundreds of calculations, tweaking the parameters a little bit each time, until an expected outcome is reached (or comes close). After completing my "brute force loop", and running some tests, I was a little disappointed to find that only 400 calculations took 2.5 seconds to complete on Firefox 13.

Then, it hit me, I was doing 3 DOM lookups with jQuery in each loop, i.e.


for(var i = 0; i < 400; i++) {
  // brute force stuff..
  param = $(this).parent().parent().siblings('.myfield').val();
  // more DOM lookups

  // formula that uses param
}

So, I was ecstatic, assuming that if I set a variable to the field values, outside of the for loop, I'll cut execution time dramatically.

var param = $(this).parent().parent().siblings('.myfield').val();
for(var i = 0; i < 400; i++) {
  // brute force stuff..
  // formula that uses param
}

I logged the time for both approaches, and much to my surprise, I only saved about 2 or 3% by dropping the DOM lookups.

Just thought I let everyone in on that, in case you are looking for ways to optimize your code – start somewhere else!

Oh, and as a little bonus, interesting to see how quickly different browsers run JS. My code was executed in the times listed below by browser:

FF 13:         2.5 seconds
IE    9:         1.7 seconds
IE    8:         5.1 seconds
IE    7:         4.8 seconds (what did they do wrong in IE 8!)
Chrome 19:  1.5 seconds
Safari 5.1     1.8 seconds

Nice going Google!
 

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *