Reputation: 85
Is it faster to call a javascript function defined globally or as a property of a global variable?
For example:
Option 1
.html:
<input type="checkbox" name="" value="" onClick="dofind()">
.js:
function dofind() { /* code */ }
Option 2
.html:
<input type="checkbox" name="" value="" onClick="x.dofind()">
.js:
var x = {
dofind: function() { /* code */ }
}
Upvotes: 1
Views: 742
Reputation: 1609
You will not notice any performance difference unless you have thousands of such event handlers loaded on the page. When you have thousands of elements loaded on the page with event handlers, the time taken to attach the event handlers is going to be the least of your problem any way.
Upvotes: 0
Reputation: 147413
If you consider the scope chain of the event listener, in the first case it must resolve the identifier dofind on the objects on the listener's scope chain. Presumably it will not be found on any intermediate object and will be found on the global object. It will then be called.
In the second case, the identifier x must be resolved on a similar (identical?) scope chain, and once found, the identifier dofind must be found as a property of that object.
Logic says that the second method is slower for being longer. However, javascript engines can optimise scope chains and property access if they wish. It is quite likely (in modern browsers) that subsequent calls to dofind will be made directly, without reference to the scope chain unless the engine believes the chain may have been altered.
Testing in various browsers will reveal which optimise such calls and which don't. I think you'll find that in overall application performance, the difference in the call is negligible, particularly as resolving the identifier will occur much faster than a user can initiate a sequence of click events (probably by a factor of 1,000 or more).
Upvotes: 2
Reputation: 3841
Calling a function in a local scope is insignificantly faster. You would need to be making millions of calls before its even noticeable, which isn't the case in an onclick
handler.
Neither of those methods are ideal, though. You are better off taking the unobtrusive route by adding an onclick
event listener after the DOM has loaded.
Upvotes: 3