PDA

View Full Version : Efficient JavaScript article



LesJ
1 Dec 2011, 8:45 AM
FYI

Here's an interesting JS article:

http://dev.opera.com/articles/view/efficient-javascript/

These points were new to me:

8. Use strings accumulator-style
9. Primitive operations can be faster than function calls

Take a look at the Ext.draw.CompositeSprite.getBBox() method.

It uses Math.min and Math.max in a very tight loop. I think we could apply point #9 here :)

mitchellsimoens
1 Dec 2011, 10:01 AM
I would have to agree although I wouldn't expect too big of performance bump. Every little bit counts though I guess :)

LesJ
25 Jan 2012, 5:33 AM
FYI
Take a look at the Ext.draw.CompositeSprite.getBBox() method.

It uses Math.min and Math.max in a very tight loop. I think we could apply point #9 here :)

I just checked the nightly build. I see that the CompositeSprite.getBBox method can skip sprites from bbox calculations when the sprite has the bboxExcluded (true) attribute. This is a very simple an effective feature. I hope this is not just for internal use. I have a large number of sprites that can be excluded, so this should speed up bbox calculations.

LesJ
23 Feb 2012, 7:32 AM
I would have to agree although I wouldn't expect too big of performance bump. Every little bit counts though I guess :)

The getBBox method could be optimized further by assigning Max.min and Math.max to a local variable. This would reduce scope traversal.

The bold vars are not used.

I like that you can exclude sprites from BBox calculations. This was added in B3.

var max = Math.max


getBBox: function() {
var i = 0,
sprite,
bb,
items = this.items,
len = this.length,
infinity = Infinity,
minX = infinity,
maxHeight = -infinity,
minY = infinity,
maxWidth = -infinity,
maxWidthBBox, maxHeightBBox;

for (; i < len; i++) {
sprite = items[i];
if (sprite.el && ! sprite.bboxExcluded) {
bb = sprite.getBBox();
minX = Math.min(minX, bb.x);
minY = Math.min(minY, bb.y);
maxHeight = Math.max(maxHeight, bb.height + bb.y);
maxWidth = Math.max(maxWidth, bb.width + bb.x);
}
}

return {
x: minX,
y: minY,
height: maxHeight - minY,
width: maxWidth - minX
};
}