These do make some sense. Avoiding lookups on the global object does
make a difference (but as with all optimizations - don't do it unless
you have profiled and found it to make a signficant contribution).
Your hint about the length of the scope chain got me thinking about
making it longer - so I did. However, avoiding global lookups still
doesn't make a lot of difference. I also made the comparison in the
same scope as the function running the loop so that only the undefined
lookup should use the scope chain.
IE:
Global undefined level 0: 172
Global undefined level 1: 234
Global undefined level 2: 281
Local level 0: 47
Local level 2: 156
Firefox:
Global undefined level 0: 2
Global undefined level 1: 153
Global undefined level 2: 151
Local level 0: 2
Local level 2: 124
Performance seems to be enhanced more by executing statements as
global code than messing with local declarations of global variables.
Here's the new code:
<script type="text/javascript">
function testRef(n) {
var i = n, msg = [], f, s, t;
s = new Date();
while (i--) {
(t === undefined);
}
f = new Date();
msg.push('Global undefined level 0: ' + (f - s));
function level1() {
i = n;
s = new Date();
var t;
while (i--) {
(t === undefined);
}
f = new Date();
msg.push('\nGlobal undefined level 1: ' + (f - s));
}
level1();
function level2() {
(function() {
i = n;
s = new Date();
var t;
while (i--) {
(t === undefined);
}
f = new Date();
msg.push('\nGlobal undefined level 2: ' + (f - s));
})();
}
level2();
i = n;
s = new Date();
var UNDEFINED = undefined;
while (i--) {
(t === UNDEFINED);
}
f = new Date();
msg.push('\nLocal level 0: ' + (f - s));
function local2() {
(function() {
i = n;
s = new Date();
var UNDEFINED = undefined;
var t;
while (i--) {
(t === UNDEFINED);
}
f = new Date();
msg.push('\nLocal level 2: ' + (f - s));
})();
}
local2();
document.getElementById('div0').innerHTML = msg.join('<br>');
}
window.onload = function(){testRef(500000);};
</script>
Taking a copy to be safe against overwriting also makes sense,
especially in library code that might be combined with other
libraries.
I can understand that perspective. However, it woud be better to use:
var UNDEFINED;
so that it is obvious within the code that it has been defined within
the script. Also, using:
var undefined = undefined;
means that if some other script that assigns it an unexpected value
runs first, the "local" undefined will get that unexpected value.