简体   繁体   English

如何优化Javascript查找?

[英]How to optimize Javascript lookups?

According to Javascript's major implementations, the lookup for variables and functions starts at the spot and traversing upwards until the global objects. 根据Javascript的主要实现,变量和函数的查找从现场开始并向上遍历直到全局对象。

Now lets say you're building larger OOP based frameworks and you need to call safety checks all over the place, then it doesnt seem right to call those things that way : "xapp.utils.isValidString(var). The same applies to constants, enumerations and flags which take place everywhere usally. 现在假设您正在构建更大的基于OOP的框架,并且需要在整个地方调用安全检查,那么以这种方式调用这些东西似乎是正确的:“xapp.utils.isValidString(var)。这同样适用于常量,通用和旗帜通常发生在任何地方。

I am not quite sure whether this has impacts on the answer but we're doing all in Dojo and we are pretty aware about its lang.mixin method. 我不太确定这是否会对答案产生影响,但我们在Dojo中做了所有事情,我们非常了解它的lang.mixin方法。

However, the idea is to mixin an obvious and minimal set of functions and objects into the target objects local scope by using the constructor or prototype. 但是,我们的想法是通过使用构造函数或原型将一组明显的和最小的函数和对象混合到目标对象的本地范围中。 Would you consider this to be a legal way ? 你认为这是合法的方式吗?

Then what about caching and reusing those prepared objects ? 那么缓存和重用那些准备好的对象呢? Which kind of buffer you would choose ? 你会选择哪种缓冲? To me it looks rather like an ring buffer. 对我而言,它看起来就像一个环形缓冲区。

I am still learning JS optimization and I would be happy about your thoughts ! 我还在学习JS优化,我很高兴你的想法!

For your reference, here some common tips about scope managment explained by a guru : http://googlecode.blogspot.com.es/2009/06/nicholas-c-zakas-speed-up-your.html 供大家参考,这里有一些关于范围管理的常见技巧: http//googlecode.blogspot.com.es/2009/06/nicholas-c-zakas-speed-up-your.html

Update : We need to focus only on modern desktop and mobile browsers, leaving IE totally out ! 更新:我们需要只关注现代桌面和移动浏览器,让IE完全退出! Also, we're familiar with Dojo's build chain, enabling conditional compiling per platform (If that matters). 此外,我们熟悉Dojo的构建链,支持每个平台的条件编译(如果这很重要)。

As for identifier resolution, ie direct references, I recommend that you switch to the strict language (if you already haven't), aka "strict mode". 至于标识符解析,即直接引用,我建议你切换到严格的语言(如果你还没有),也就是“严格模式”。 The strict language is statically scoped, which enables JS engines to statically bind the identifiers, which results in better performance during program execution (the identifiers have already been bound during compilation). 严格语言是静态范围的,它使JS引擎能够静态绑定标识符,从而在程序执行期间获得更好的性能(标识符在编译期间已被绑定)。


As for property look-ups, if you have long chains, eg 至于财产查询,如果你有长链,例如

foo.bar.baz.method1();
foo.bar.baz.method2();

the usual solution (not just for performance, but also to avoid code repetition) is to store the right-most object into a local variable: 通常的解决方案(不仅仅是为了提高性能,还要避免代码重复)是将最右边的对象存储到局部变量中:

var baz = foo.bar.baz;

baz.method1();
baz.method2();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM