且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

JavaScript用回调替换-性能问题

更新时间:2023-12-05 12:49:58

+1向安妮(Annie)关于性能基准测试.

+1 to Annie about perf benchmarks.

但我会同意的

return lookup[match] || match;

不仅是对属性的单次检索(而不是-如您先前的示例中所示,是对两个对象的优化除外),而且它也较短,并且(较短的代码并不总是如此)对于任何经验不足的JavaScript编码器来说,都更清晰.它会给新手带来一些麻烦,但是要教给新手的第一件事就是特殊的(和出色的)||&&在JavaScript中的工作方式,所以...

Not only is it just a single retrieval of the property (rather than -- barring optimization -- two, as in your earlier examples), but it's also shorter and (this is not always true of shorter code) clearer to any half-experienced JavaScript coder. It will tend to throw novices a bit, but one of the first things you want to teach novices is how the special (and excellent) || and && work in JavaScript, so...

在某些实现中,它也可以解决几个(非常)边缘情况. (示例:'toString' in {}应该为true [所有对象都从Object原型继承toString],但是在Microsoft的JScript中为false.)

It also works around a couple of (very) edge cases in some implementations. (Example: 'toString' in {} should be true [all objects inherit toString from the Object prototype], but it's false in Microsoft's JScript.)

关于优化:除非显而易见,否则不要使循环条件成为必须进行计数的函数,如果它可以是不变的,请避免不必要地重复查找),甚至不必进行是否值得担心的一般讨论这些东西在您遇到问题之前(有时称为过早优化"),对于一般网络的JavaScript来说尤其如此.不同的微优化在不同的实现中会有不同的结果,有时结果是矛盾的(Internet Explorer中的"A"更好,而在FireFox中则更差,反之亦然).通常,您要等到看到一个特定的问题,然后再解决该特定的问题.

Regarding optimizing: Barring the glaringly obvious (don't make your loop condition a function that has to go count things if it can be an invariant, avoid duplicating lookups unnecessarily), even absent the general discussion of whether it's worth worrying about this stuff before you see a problem (sometimes called "premature optimization"), it's especially true of JavaScript for the general web. Different micro-optimizations have different results in different implementations, sometimes conflicting results ("A" being better in Internet Explorer but much worse in FireFox, and the converse). Mostly it's a matter of wait until you see a specific problem, then address that specific problem.

我更喜欢简单明了,除非我有充分的理由相信笨拙的东西会给我带来可衡量的,真实的改进.

I prefer simplicity and clarity, unless I have a strong reason to believe that something clunkier is going to give me a measurable, real-world improvement.