Skip to content

Style and typography fixes and code style adherence in the Performance section. #334

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 12 additions & 15 deletions page/performance/append-outside-loop.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,52 +6,49 @@ attribution:
- jQuery Fundamentals
---

Touching the DOM comes at a cost; if you're appending a lot of elements to the
DOM, you will want to append them all at once, rather then one at a time. This is common problem when appending elements within a loop.
Touching the DOM comes at a cost; if you're appending a lot of elements to the DOM, you will want to append them all at once, rather then one at a time. This is common problem when appending elements within a loop.

```
$.each( myArray, function( i, item ) {

var newListItem = "<li>" + item + "</li>";
var newListItem = "<li>" + item + "</li>";

$("#ballers").append( newListItem );
$( "#ballers" ).append( newListItem );

});
```

One common technique is to leverage a document fragment. During each iteration
of the loop, you append the element to the fragment rather than the DOM
element. After the loop, just append the fragment to the DOM element.
One common technique is to leverage a document fragment. During each iteration of the loop, you append the element to the fragment rather than the DOM element. After the loop, just append the fragment to the DOM element.

```
var frag = document.createDocumentFragment();

$.each( myArray, function( i, item ) {

var newListItem = document.createElement("li");
var itemText = document.createTextNode( item );
var newListItem = document.createElement( "li" );
var itemText = document.createTextNode( item );

newListItem.appendChild( itemText );
newListItem.appendChild( itemText );

frag.appendChild( newListItem );
frag.appendChild( newListItem );

});

$("#ballers")[ 0 ].appendChild( frag );
$( "#ballers" )[ 0 ].appendChild( frag );
```

Another technique, which is quite simple, is to build up a string during each iteration of the loop. After the loop, just set the html of the DOM element to that string.
Another technique, which is quite simple, is to build up a string during each iteration of the loop. After the loop, just set the HTML of the DOM element to that string.

```
var myHtml = "";

$.each( myArray, function( i, item ) {

myHtml += "<li>" + item + "</li>";
myHtml += "<li>" + item + "</li>";

});

$("#ballers").html( myHtml );
$( "#ballers" ).html( myHtml );
```

There are of course other techniques you could certainly test out; a great way to test the performance of these is through a site called [jsperf](http://jsperf.com). This site allows you to benchmark each technique and visually see how it performs across all the browsers.
5 changes: 2 additions & 3 deletions page/performance/cache-loop-length.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,15 +6,14 @@ attribution:
- jQuery Fundamentals
---

In a for loop, don't access the length property of an array every time; cache
it beforehand.
In a for loop, don't access the length property of an array every time; cache it beforehand.

```
var myLength = myArray.length;

for ( var i = 0; i < myLength; i++ ) {

// do stuff
// do stuff

}
```
7 changes: 3 additions & 4 deletions page/performance/detach-elements-before-work-with-them.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,16 +6,15 @@ attribution:
- jQuery Fundamentals
---

The DOM is slow; you want to avoid manipulating it as much as possible. jQuery
introduced `$.fn.detach` in version 1.4 to help address this issue, allowing you
to remove an element from the DOM while you work with it.
The DOM is slow; you want to avoid manipulating it as much as possible. jQuery introduced `$.fn.detach` in version 1.4 to help address this issue, allowing you to remove an element from the DOM while you work with it.

```
var $table = $("#myTable");
var $table = $( "#myTable" );
var $parent = $table.parent();

$table.detach();

// ... add lots and lots of rows to table

$parent.append( $table );
```
32 changes: 14 additions & 18 deletions page/performance/dont-act-on-absent-elements.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,40 +6,36 @@ attribution:
- jQuery Fundamentals
---

jQuery won't tell you if you're trying to run a whole lot of code on an empty
selection — it will proceed as though nothing's wrong. It's up to you to verify
that your selection contains some elements.
jQuery won't tell you if you're trying to run a whole lot of code on an empty selection – it will proceed as though nothing's wrong. It's up to you to verify that your selection contains some elements.

```
// BAD: this runs three functions
// before it realizes there's nothing
// in the selection
$("#nosuchthing").slideUp();
// Bad: This runs three functions before it
// realizes there's nothing in the selection
$( "#nosuchthing" ).slideUp();

// Better
var $mySelection = $("#nosuchthing");
// Better:
var $mySelection = $( "#nosuchthing" );

if ( $mySelection.length ) {

$mySelection.slideUp();
$mySelection.slideUp();

}

// BEST: add a doOnce plugin
jQuery.fn.doOnce = function( func ){
// Best: Add a doOnce plugin.
jQuery.fn.doOnce = function( func ) {

this.length && func.apply( this );
this.length && func.apply( this );

return this;
return this;

}

$("li.cartitems").doOnce(function() {

$( "li.cartitems" ).doOnce(function() {


// make it ajax! \o/

// make it ajax! \o/


});
```

This guidance is especially applicable for jQuery UI widgets, which have a lot
of overhead even when the selection doesn't contain elements.
This guidance is especially applicable for jQuery UI widgets, which have a lot of overhead even when the selection doesn't contain elements.
56 changes: 23 additions & 33 deletions page/performance/optimize-selectors.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,66 +6,56 @@ attribution:
- jQuery Fundamentals
---

Selector optimization is less important than it used to be, as more browsers
implement document.querySelectorAll() and the burden of selection shifts from
jQuery to the browser. However, there are still some tips to keep in mind.
Selector optimization is less important than it used to be, as more browsers implement `document.querySelectorAll()` and the burden of selection shifts from jQuery to the browser. However, there are still some tips to keep in mind.

## ID-Based Selectors

Beginning your selector with an ID is always best.

```
// fast
$("#container div.robotarm");
// Fast:
$( "#container div.robotarm" );

// super-fast
$("#container").find("div.robotarm");
// Super-fast:
$( "#container" ).find( "div.robotarm" );
```

The `$.fn.find` approach is faster because the first selection is handled
without going through the Sizzle selector engine — ID-only selections are
handled using `document.getElementById()`, which is extremely fast because it is
native to the browser.
The `$.fn.find` approach is faster because the first selection is handled without going through the Sizzle selector engine – ID-only selections are handled using `document.getElementById()`, which is extremely fast because it is native to the browser.

## Specificity

Be specific on the right-hand side of your selector, and less specific on the
left.
Be specific on the right-hand side of your selector, and less specific on the left.

```
// unoptimized
$("div.data .gonzalez");

// optimized
$(".data td.gonzalez");
// Unoptimized:
$( "div.data .gonzalez" );

// Optimized:
$( ".data td.gonzalez" );
```

Use `tag.class` if possible on your right-most selector, and just tag or just
`.class` on the left.
Use `tag.class` if possible on your right-most selector, and just tag or just `.class` on the left.

## Avoid excessive specificity.
## Avoid Excessive Specificity

```
$(".data table.attendees td.gonzalez");
$( ".data table.attendees td.gonzalez" );

// better: drop the middle if possible
$(".data td.gonzalez");
// Better: Drop the middle if possible.
$( ".data td.gonzalez" );
```

A "flatter" DOM also helps improve selector performance, as the selector engine
has fewer layers to traverse when looking for an element.
A "flatter" DOM also helps improve selector performance, as the selector engine has fewer layers to traverse when looking for an element.

## Avoid the Universal Selector

Selections that specify or imply that a match could be found anywhere can be
very slow.
Selections that specify or imply that a match could be found anywhere can be very slow.

```
$(".buttons > *"); // extremely expensive
$(".buttons").children(); // much better
$( ".buttons > *" ); // Extremely expensive.
$( ".buttons" ).children(); // Much better.

$(".gender :radio"); // implied universal selection
$(".gender *:radio"); // same thing, explicit now
$(".gender input:radio"); // much better
$( ".gender :radio" ); // Implied universal selection.
$( ".gender *:radio" ); // Same thing, explicit now.
$( ".gender input:radio" ); // Much better.
```
12 changes: 6 additions & 6 deletions page/performance/use-stylesheets-for-changing-css.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ attribution:
- jQuery Fundamentals
---

If you're changing the CSS of more than 20 elements using `$.fn.css`, consider
adding a style tag to the page instead for a nearly 60% increase in speed.
If you're changing the CSS of more than 20 elements using `$.fn.css`, consider adding a style tag to the page instead for a nearly 60% increase in speed.

```
// fine for up to 20 elements, slow after that
$("a.swedberg").css("color", "#asd123");
// Fine for up to 20 elements, slow after that:
$( "a.swedberg" ).css( "color", "#0769ad" );

$("<style type=\"text/css\">a.swedberg { color : #asd123 }</style>")
.appendTo("head");
// Much faster:
$( "<style type=\"text/css\">a.swedberg { color: #0769ad }</style>")
.appendTo( "head" );
```