A Rule of Thumb When DOM Scripting

原则是:尽可能的不要接触DOM(touch the DOM lightly, and stay within ECMAScript as much as possible).

Here is an example

function aBadInnerHTMLLoop() {
    for (var i = 0; i < 15000; i++) {
        document.getElementById('here').innerHTML += 'a';
    }
}

上面这段代码的效率之低下,令人叹为观止,在我的Chrome下面,执行了4900ms!

function aBetterInnerHTMLLoop() {
    var str = '';
    for (var i = 0; i < 15000; i++) {
        str += 'a';
    }
    document.getElementById('here').innerHTML = str;
}

上面这段代码只执行了4ms。。。

下面我引用一段文献[High Performance JavaScript]来说明为什么DOM的执行如此低下。

DOM in the Browser World
The Document Object Model(DOM) is a language-independent application interface(API) for working with XML and HTML documents. … so it’s common across browsers to keep DOM and JavaScript implementions indepent of each other, this makes DOM scripting inherently slow. Because simply having two separate pieces of functionality interfaceing with eath other will always come at a cost. An excellent analogy is to think of DOM as piece of land and JavaScript as another piece of land, both connected with a toll bridge. Every time your EMACScript needs access to the DOM, you have to cross this bridge and pay the performance toll fee. The more you work with the DOM, the more you pay So the general recommendation is to cross that bridge as few times as possible and strive to stay in ECMAScript land.