0

One of the first things I learned when writing JavaScript was that it bad practice to set variables on window and polluting the global namespace.

Looking around there are loads of articles as there are SO questions on why it is considered bad practice and even how to measure the amount of objects stored (here).

But even if I can get the amount of objects being stored on window I have never read anything about the actual performance hit taken by cluttering window.

Question:
Are there any examples showing how name space pollution drains performance?

Community
  • 1
  • 1
frequent
  • 27,643
  • 59
  • 181
  • 333
  • 1
    There is a performance hit, but IMO the bigger issue is name conflicts. Often if your code is large enough to have performance issues from this, it is large enough to be very difficult to avoid name clashes. – Dark Falcon Jun 20 '14 at 13:03
  • Good point. Still curious if there is any "evidence" – frequent Jun 20 '14 at 13:04
  • I imagine it is browser dependent. You could try fiddling with these and see what you get: [with namespace pollution](http://jsperf.com/global-namespace-pollution), [without namespace pollution](http://jsperf.com/global-namespace-pollution/2) – Dark Falcon Jun 20 '14 at 13:20
  • I modified it a little. So you have your [2nd revision ("no pollution")](jsperf.com/global-namespace-pollution/2/) and my [3rd revision ("polluted")](http://jsperf.com/global-namespace-pollution/3). Your first test was tainted because you were picking a value from your `window[array]` vs declaring a variable. What do you think? – frequent Jun 20 '14 at 13:32
  • I think it is interesting to note the difference between low and high when a lot of keys are present. Also, it seems to be about a 2x difference in ops/sec between the two tests here. – Dark Falcon Jun 20 '14 at 13:40
  • Yup. I will later try a similar thing with more realistic setup = one revision with plugins like ... jQuery, jQuery Mobile... The other one without. This would be a more realistic scenario. – frequent Jun 20 '14 at 14:15

0 Answers0