SO i totally understand why we should namespace in javascript, but is it mainly for organizational purpose开发者_Python百科s and to keep the global namespace uncluttered?. Does namepacing actually help in performance of the browser/JS engine. Just wondering what your thoughts were. Thanks
It technically hinders performance but not much, depending on how deep you start going. Silobox (http://www.silobox.com/) is a JavaScript performance benchmarking tool and we wrote a test that tests this very thing. We found that the deeper an object was nested, the longer accessing those properties took.
So for optimum speed, I recommend adding global shortcut functions to your code.
Assume you have:
var mycompany.myproj.Something = function(){ ... };
It's good practice to include
var MCSomething = mycompany.myproj.Something;
That way, when the JS engine looks up MCSomething
, it doesn't have to climb down any trees. Google Maps uses this approach.
There shouldn't be any noticeable affect on performance from using namespaces. The primary reasons are just what you mentioned: keeping the global namespace clean (to avoid naming conflicts) and organization.
精彩评论