Answer the question
In order to leave comments, you need to log in
Is there any way to optimize this javascript code?
move() {
let layerOffset = this.layerOffset,
currentLayerOffset = this.currentLayerOffset,
layerMoveBraking = this.processedConfig.layerMoveBraking,
border = this.border,
points = this.points;
this.currentLayerOffset = {
'1': {
x: layerOffset[1].x + (currentLayerOffset[1].x - layerOffset[1].x) * layerMoveBraking,
y: layerOffset[1].y + (currentLayerOffset[1].y - layerOffset[1].y) * layerMoveBraking
},
'2': {
x: layerOffset[2].x + (currentLayerOffset[2].x - layerOffset[2].x) * layerMoveBraking,
y: layerOffset[2].y + (currentLayerOffset[2].y - layerOffset[2].y) * layerMoveBraking
},
'3': {
x: layerOffset[3].x + (currentLayerOffset[3].x - layerOffset[3].x) * layerMoveBraking,
y: layerOffset[3].y + (currentLayerOffset[3].y - layerOffset[3].y) * layerMoveBraking
}
};
points.forEach(function (point) {
point.coordinatesOnLayer.x += point.speed.x;
point.coordinatesOnLayer.y += point.speed.y;
point.coordinates.x = point.coordinatesOnLayer.x + currentLayerOffset[point.layer].x;
point.coordinates.y = point.coordinatesOnLayer.y + currentLayerOffset[point.layer].y;
if (point.coordinatesOnLayer.x < border.left) {
point.speed.x = Math.abs(point.speed.x)
} else if (point.coordinatesOnLayer.x > border.right) {
point.speed.x = -Math.abs(point.speed.x)
}
if (point.coordinatesOnLayer.y < border.top) {
point.speed.y = Math.abs(point.speed.y)
} else if (point.coordinatesOnLayer.y > border.bottom) {
point.speed.y = -Math.abs(point.speed.y)
}
}, this)
}
Answer the question
In order to leave comments, you need to log in
The loop for (let i = 0, len = points.length; i < len; i++)
will be about an order of magnitude faster than Array#forEach - but it depends on the number of elements in the array, if there are ten of them, then don't care. Also, check if your iterator is executed in a specific context, but this is not used anywhere in the function body.
There is nothing to optimize in the above code, it's just simple arithmetic. I suspect that you have brakes in another place - where it is displayed on the screen. If this case is moving divas, then look for techniques to reduce reflow and repaint. If these are some canvas sprites, it might be worth rendering in WebGL (take pixi.js).
Well, yes, check, check and check again with a profiler. Thoughtfully.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question