Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Thursday, March 29, 2012

jQuery .on performance

jQuery's .on() function is very useful.  It allows you to bind event listeners for elements that haven't yet been created.  On pages where you're dynamically adding elements, this can make the code much cleaner and unobtrusive.  Rather than attaching the event handler to every newly created element one at a time, simply attach a class to all new elements, and call .on() for this class name with the event handler function once when the page loads for the first time.

.on() simply grabs the event when it happens at the higher level that you specify (usually document or a container div), checks if the element that caused the event matches any of the selectors for any added .on() calls, and if so calls your handler.

This functionality is also provided by .live(), but as of jquery 1.7, this function is deprecated. Use .on() instead.

tl;dr

Use .on()! Using .on() to capture the event over attaching a handler directly to each element has virtually no performance impact when the event is triggered, even when there are a huge number of unique elements with their own .on() handler on the page. However, using .on() does have a very noticeable performance advantage when generating/rendering elements. So any performance arguments against .on() are invalid.

Measuring Performance

Because of the way that it works, you may think that there is a performance hit to using .on() instead of attaching the handler to each element when it's created.  So I decided to do some extensive testing to see if this was the case.

I wrote a simple test page that dynamically generates lots of clickable elements.  See this page at http://coordinatecommons.com/jquery-on-test.html.

For each test case, there are two different measures of performance. First is how long it takes to dynamically generate the elements. When using .on, this is mostly the time to simply generate the DOM elements. However, when using .click to bind the listener one at a time, it takes longer because of the added step to attach the listener at this point.

The second measure is how long it takes for the callback to be called after clicking. For this, the time is how long between the parent container's mousedown event and the event handler being called. Because the initial time is on mousedown, there is some variability test to test based on how much time it took me to let go of the mouse button. So any result here can vary by 100-150ms, the results should not be analyzed any more precise than 150ms intervals. And realistically you can probably subtract on average 80-100ms from each of these to get the actual times.

Test Cases

  1. Generate 10,000 divs with the same class name, using .on - generate 10,000 of the same type of element that will all use the same event handler. Attach the same class name to all elements, one call to .on.
  2. Generate 10,000 divs with one of 100 different classes names, click handler using .on - 100 different event handlers, 10,000 total elements. .on is called 100 times
  3. Generate 1,000 divs with unique classes, click handler using .on - 1,000 unique event handlers for 1,000 elements. .on is called 1,000 times
  4. Generate 10,000 divs with unique classes, click handler using .on - 10,000 unique event handlers for 10,000 elements. .on is called 10,000 times
  5. Generate 1,000 divs with unique IDs, click handler using .click - attach an event listener to each element with .click as the element is being added.
  6. Generate 10,000 divs with unique IDs, click handler using .click - same as above but with 10,000 elements.

Tests 1 and 6 are the ones that will really evenly compare performance of attaching a handler to each element as it's added versus using .on.

Test Conditions

For Chrome, Firefox, and IE9, a desktop machine (quad core 3 GHz, 8 gigs of RAM) running Windows 7 Professional 64 bit was used. For IE6, 7, and 8, a Windows XP Virtualbox VM running on the desktop machine above was used.

Performance Results Table

Chrome 17 Firefox 11 IE9 IE8 IE7 IE6
Test 1 RENDER- 10K same class/handler .on 912 ms 271 ms 3020 ms 3142 ms 3668 ms 3877 ms
Test 1 CLICK - 10K same class/handler .on 70 ms 74 ms 110 ms 121 ms 110 ms 133 ms
Test 2 RENDER - 10K one of 100 class .on 1081 ms 344 ms 3270 ms 4857 ms 5732 ms 5965 ms
Test 2 CLICK - 10K one of 100 .on 94 ms 114 ms 111 ms 131 ms 137 ms 95 ms
Test 3 RENDER - 1,000 unique classes .on 328 ms 164 ms 832 ms 1483 ms 1385 ms 1021 ms
Test 3 CLICK - 1,000 unique classes .on 140 ms 162 ms 107 ms 140 ms 107 ms 120 ms
Test 4 RENDER - 10,000 unique classes .on 2772 ms 1397 ms 14050 ms 15602 ms 47609 ms 29614 ms
Test 4 CLICK - 10,000 unique classes .on 245 ms 252 ms 149 ms 421 ms 409 ms 442 ms
Test 5 RENDER - 1,000 unique ID .click 281 ms 175 ms 898 ms 1983 ms 2133 ms 2023 ms
Test 5 CLICK - 1,000 unique ID .click 106 ms 112 ms 100 ms 103 ms 100 ms 90 ms
Test 6 RENDER - 10,000 unique ID .click 2826 ms 1576 ms 14618 ms 50673 ms 65835 ms 66606 ms
Test 6 CLICK - 10,000 unique ID .click 80 ms 113 ms 106 ms 94 ms 100 ms 130 ms

Results


Using .on() to capture the event over attaching a handler directly to each element has virtually no performance impact when the event is triggered, even when there are a huge number of unique elements with their own .on() handler on the page. I expected there to be at least some noticeable lag in the click times when there are 10,000 unique elements, but it was only noticeable on IE8 and below and just barely noticeable. And, that's with using .on() in a way that it shouldn't be used. Test 1 is the way that .on() should be used, and it performs wonderfully. Times are identical to test 6, where each element has a directly attached handler.

However, using .on() does have a very noticeable performance advantage when generating/rendering elements. This is obvious in test 1, the render times for the same number of elements is anywhere from 7 to 17 times faster than attaching the handler to each rendered element!

So based on this my recommendation is to use .on() to attach event handlers any time there will be more than one element added with the same function used for the handler.

Other observations


Another thing I found interesting is that on nearly all tests, Firefox is the fastest. Chrome is definitely behind Firefox for these tests. Also, seeing the numbers for IE8, it's a real shame that nearly 25% of the world is using this browser. Microsoft did very little to improve performance in between 6 and 8, and performance improvements in 9 many times are very small. Microsoft, IE10 better be blazingly fast! And, please, work on getting Windows XP users to upgrade to IE10. Firefox and Chrome run perfectly well on Windows XP, your own browser should as well.

Wednesday, January 4, 2012

Rails 3.1 "Could not find a JavaScript runtime" error

I just got my first Rails 3.1 on JRuby project created.  However I keep getting the error "Could not find a JavaScript runtime ..." when trying to do pretty much anything with it.  After digging in to this some, it turns out that with the addition of CoffeeScript in 3.1, Rails needs to run Javascript code natively.  A gem called execjs was added to Rails to allow this.  EXCEPT, execjs itself needs something else to actually evaluate the Javascript.    See https://github.com/sstephenson/execjs for a list.  If you're running in Mac or Windows, you're good, there are system libraries to do it.  But if you're in Linux, unless you have node.js installed, it won't work.

Let me repeat that.  Rails 3.1 apps by default will NOT work in Linux, unless you have node.js installed.  This is absolutely ridiculous... guess what Rails team, a lot of people are developing in Linux and not Mac.  I understand how stuff not working in Windows is released, but Linux??

So to get things to work you'll need to add one of the gems listed on the execjs page.  If you're running the MRI Ruby, just add:

gem 'therubyracer'

to your Gemfile.  I've read a lot of complaints about therubyracer.  But it appears to be the most popular.  If you're running JRuby like me, add:

gem 'therubyrhino'

to your Gemfile.  I've verified that this works correctly.

FOLLOW UP 1/13/2012:
See my comments.  I have made a fix to Rails to put the appropriate gem in the Gemfile if you are in Linux, and issued pull requests to the Rails core to incorporate this code.  They have made some comments on it, hopefully it will be pulled in to Rails soon.

Sunday, July 26, 2009

Javascript Bind: Making Me Hate Javascript A Little Less

I've been working on a Javascript intensive section of my web app lately, and it's reminding me of how much I hate Javascript. Everything seems so haphazard and chaotic compared to writing Ruby code. The Prototype effort has made things less painful but it's still not fun.

One area of Javascript in particular that's always given me trouble is dynamically creating elements that have event handlers. Let me give an example. Say you want to generate 5 links, each with a different value.

  <div id="buttons">
<input type="button" value="Generate links" onclick="generateLinks()" />
<script type="text/javascript">
function generateLinks() {
for (var i=0; i < 5; i++) {
var a = document.createElement('a');
a.linkNum = i;
a.onclick = function() { alert("i is " + i + ", linkNum is " + this.linkNum); };
a.href = "javascript:void(0)";
a.innerHTML = "Link " + i;
document.getElementById('buttons').appendChild(a);
}
}
</script>
</div>

When you run the code, the value of the variable i inside the function is always the same. That's because it essentially becomes a global variable. So when the event occurs and the function is run, the current value of i is reported. One hackish way around this is to assign a custom property to the element that you are creating. When the function is run, the keyword "this" refers to the element that the event occurs on, so you can easily access the custom property of the element, which was assigned when the element was created.

However, in more complex Javascript, you may want to access the object that you're generating the event handler code in. Let me give an example:

  <div id="buttons">
<input type="button" value="Generate links" onclick="generateLinks()" />
<script type="text/javascript">
var linkGenerator;
function generateLinks() {
linkGenerator = new Object();
linkGenerator.val = "Hello from link generator";
linkGenerator.showAlert = function(index) {
alert(this.val + " " + index);
};
linkGenerator.generateLink = function(index) {
var a = document.createElement('a');
a.linkNum = index;
a.onclick = function() { this.showAlert(index); };
a.href = "javascript:void(0)";
a.innerHTML = "Link " + index;
document.getElementById('buttons').appendChild(a);
};
for (var i=0; i < 5; i++) {
linkGenerator.generateLink(i);
}
}
</script>
</div>

If you run this code, you'll see an error in Firebug: "this.showAlert is not a function". That's because when the event handler function gets run, "this" does not refer to the linkGenerator object. this refers to the a element. So there is no "this.showAlert" property of the a object.


This is where the Prototype bind function comes to the rescue! Simply add .bind() to the end of any function, and pass the object that you want "this" to be when the function is called. Example:

  <div id="buttons">
<input type="button" value="Generate links" onclick="generateLinks()" />
<script type="text/javascript">
var linkGenerator;
function generateLinks() {
linkGenerator = new Object();
linkGenerator.val = "Hello from link generator";
linkGenerator.showAlert = function(index) {
alert(this.val + " " + index);
};
linkGenerator.generateLink = function(index) {
var a = document.createElement('a');
a.linkNum = index;
a.onclick = function() { this.showAlert(index); }.bind(this);
a.href = "javascript:void(0)";
a.innerHTML = "Link " + index;
document.getElementById('buttons').appendChild(a);
};
for (var i=0; i < 5; i++) {
linkGenerator.generateLink(i);
}
}
</script>
</div>

Now, when you generate the links, the "this" inside of the function will refer to linkGenerator and display the correct thing.

In addition to specifying the context for this, you can also pass other variables in to the function. Remember our first example, where we were using the variable i in the event handler, and it was always showing the last value? Well, guess what, bind can help us here too. Simply pass a list of variables in to bind after the this reference, and these variables will be available in the function, set to the values that they were at the time the function is generated, not run. Example:

  <div id="buttons">
<input type="button" value="Generate links" onclick="generateLinks()" />
<script type="text/javascript">
var linkGenerator;
function generateLinks() {
linkGenerator = new Object();
linkGenerator.val = "Hello from link generator";
linkGenerator.showAlert = function(index) {
alert(this.val + " " + index);
};
linkGenerator.generateLink = function(index) {
var a = document.createElement('a');
a.linkNum = index;
a.onclick = function(myI) { this.showAlert(index); alert("i is " + myI); }.bind(this, i);
a.href = "javascript:void(0)";
a.innerHTML = "Link " + index;
document.getElementById('buttons').appendChild(a);
};
for (var i=0; i < 5; i++) {
linkGenerator.generateLink(i);
}
}
</script>
</div>

If i is not passed in to bind and taken as a parameter to the function, i will always report as 5, like it did in the first example. By passing it in to bind, the value at that time gets preserved. Very useful stuff!

One more thing that bind does. If you want to get the event that triggered the function call, put bindAsEventListener instead of bind after the function. This will always pass event as the first parameter.

Friday, January 9, 2009

How to debug Javascript in Internet Explorer

Firebug for Firefox is an invaluable tool for debugging Javascript. And when you're writing code that uses the Prototype library, the code usually works the same in both Firefox and Internet Explorer, so can use Firebug to debug your Javascript. But for regular, non-Prototype Javascript code, and the occasional Prototype function that isn't completely browser independent, you may need to debug Javascript code from Internet Explorer to get it to work correctly. Fortunately it's pretty simple to do this, although it's not easy to find how to do this.

For Internet Explorer 8, Microsoft has bundled some developer tools. Click Tools then Developer Tools. Functionality is somewhat similar to Firebug, more similar to Chrome's developer tools, but not quite as good.

For Internet Explorer 6 or 7, you must install other tools to debug. Before you can start debugging, you will need either Visual Studio or Microsoft Script Editor. If you don't have Visual Studio, you can download the Microsoft Script Editor from Microsoft at http://www.microsoft.com/downloads/details.aspx?FamilyID=2f465be0-94fd-4569-b3c4-dffdf19ccd99&displaylang=en. From Script Editor, you can do just about everything that you can from Visual Studio, including viewing the call stack, setting break points, stepping through code, setting variables to watch, etc.


Once you have Visual Studio or Script Editor installed, from Internet Explorer, click Tools, then Internet Options. (if you're using IE7 and the menu bar is hidden, press ALT to show it). From this window, click the Advanced tab, and then uncheck "Disable script debugging (Internet Explorer".


Once you click OK here, go to the page that you wish to debug from. Then click View, Script Debugger, Open (again if you're using IE7 and the menu bar is hidden, press ALT to bring it up).

After this another window will open up asking which debugger you wish to use. Click on the one you wish to use (either Script Editor or Visual Studio), and click Yes.


If you use Script Editor, the HTML for the page you are on will be displayed. This typically doesn't help you debug the Javascript because your Javascript is probably in another file. But by default there is no window to select other files! To show the file selection window, simply click Debug, Windows, then Running Documents.

This will open up a window on the left listing all of the loaded Javascript and HTML files. Just double click on the file that your code that you wish to debug is in. Now you can set a breakpoint on a line by clicking in the gray area directly to the left of the code (or click Debug, New Breakpoint), and when you do something from the web page that will cause this Javascript to run, the Script Editor will pause execution from that line, allowing you to inspect values, view the call stack, step through code, etc. If you want to debug code that runs when your document loads, you can add the line debugger; to your Javascript, which will cause the debugger to automatically open up when the page is loaded.

While this capability isn't as comprehensive as Firebug (no viewing of requests, times, etc.), it certainly serves the purpose of allowing you to debug Javascript code from within Internet Explorer.