View Single Post
Old May 26th, 2006, 9:08 AM   #14
Cerulean
Professional Programmer
 
Cerulean's Avatar
 
Join Date: Apr 2005
Location: London, England
Posts: 459
Rep Power: 4 Cerulean is on a distinguished road
Yup, as I said further up - caching is slower. running with the cached version gives ~23 ms here. Regular document.getElementById gives ~15 ms. This is with Konqueror 3.5. On Firefox, results are less noticeable (cached version ~63 ms, non-cached ~55 ms) but still apparent.
The results really aren't that noticeable but I mean, you waste processing and programmer time by caching the output of getElementById, soo... :banana:
Test I used is below:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html>
    <head>
        <title>Caching test</title>
        <style type="text/css">
            div { padding: 3px; margin: 3px; border: 1px solid #ccc; background-color: #eef }
        </style>
        <script language="javascript" type="text/javascript">
            var cache = new Array();
            function cachedElementById(id) {
                if(typeof(cache[id]) == "undefined") {
                    cache[id] = document.getElementById(id);
                    return cache[id];
                }
                else return cache[id];
            }
            
            function test() {
                var startTime = (new Date()).getTime();
                // Get reference to a bunch of elements 500 times
                var el;
                for(var i = 0; i < 100; ++i) {
                    for(var i = 100; i < 300; ++i) {
                        // change to test accordingly
//                         el = document.getElementById("div" + i);
                        el = cachedElementById("div" + i);
                    }
                }
                alert((new Date()).getTime() - startTime + "ms");
            }
        </script>
    </head>
    <body onload="test()">
        <script language="javascript" type="text/javascript">
            // Create a tonne of elements
            var body = document.getElementsByTagName("body")[0];
            var div = null;
            for(var i = 0; i < 5000; ++i) {
                div = document.createElement("div");
                div.id = "div" + i;
                div.appendChild(document.createTextNode("Div " + i));
                body.appendChild(div);
            }
        </script>
    </body>
</html>
Cerulean is offline   Reply With Quote