我想知道是否有办法让v8内部内联函数以加速整体执行。
我有一个简单的函数可以返回像素的总能量:
function pxEnergy(x, y) {
var tmp = (y * cols + x - 1) * 4
return (data[tmp] + data[tmp + 1] + data[tmp + 2]) * data[tmp + 3];
}
我称这个为96,000,000次,我的代码需要大约2秒才能运行。
如果我在循环中将函数内联8次,例如:
xSum += -2 * (tmp = (y * cols + x - 1) * 4, (data[tmp] + data[tmp + 1] + data[tmp + 2]) * data[tmp + 3]);
现在相同的代码需要大约500毫秒才能运行。但它像罪一样丑陋:))
所以我想知道是否有人有任何魔术技巧来获得相同的加速,而无需手动内联功能。
[edit]每个请求的完整代码:
generateEnergyMap() {
// woo-hoo, nothing to do!
if (!this.dirty) { return Promise.resolve(); }
var energyMap = this.energyMap = [];
var cols = this.width;
var rows = this.height;
var data = this.data;
var pxEnergy = new Function('data', 'cols', 'x', 'y', 'var ix = (y * cols + x) * 4; return (data[ix] + data[ix + 1] + data[ix + 2]) * data[ix + 3]');
return this.imgPromise.then(function() {
for (var y = 0; y < rows; y++) {
energyMap.push([]);
for (var x = 0; x < cols; x++) {
var up = y;
var down = y < (rows - 1);
var left = x;
var right = x < (cols - 1);
var tmp;
var xSum = 0;
var ySum = 0;
if (left) {
xSum += -2 * pxEnergy(data, cols, x - 1, y); // (tmp = (y * cols + x - 1) * 4, (data[tmp] + data[tmp + 1] + data[tmp + 2]) * data[tmp + 3]);
if (up) {
xSum += tmp = -1 * pxEnergy(data, cols, x - 1, y - 1); // (tmp = ((y - 1) * cols + x - 1) * 4, (data[tmp] + data[tmp + 1] + data[tmp + 2]) * data[tmp + 3]);
ySum += tmp;
}
if (down) {
xSum += -1 * (tmp = pxEnergy(data, cols, x - 1, y + 1)); // (tmp = (tmp = ((y + 1) * cols + x - 1) * 4, (data[tmp] + data[tmp + 1] + data[tmp + 2]) * data[tmp + 3]));
ySum += tmp;
}
}
if (right) {
xSum += 2 * pxEnergy(data, cols, x + 1, y); // (tmp = (y * cols + x + 1) * 4, (data[tmp] + data[tmp + 1] + data[tmp + 2]) * data[tmp + 3]);
if (up) {
xSum += tmp = pxEnergy(data, cols, x + 1, y - 1); // (tmp = ((y - 1) * cols + x + 1) * 4, (data[tmp] + data[tmp + 1] + data[tmp + 2]) * data[tmp + 3]);
ySum += -1 * tmp;
}
if (down) {
xSum += tmp = pxEnergy(data, cols, x + 1, y + 1); // (tmp = ((y + 1) * cols + x + 1) * 4, (data[tmp] + data[tmp + 1] + data[tmp + 2]) * data[tmp + 3]);
ySum += tmp;
}
}
if (up) {
ySum += -2 * pxEnergy(data, cols, x, y - 1); // (tmp = ((y - 1) * cols + x) * 4, (data[tmp] + data[tmp + 1] + data[tmp + 2]) * data[tmp + 3]);
}
if (down) {
ySum += 2 * pxEnergy(data, cols, x, y + 1); // (tmp = ((y + 1) * cols + x) * 4, (data[tmp] + data[tmp + 1] + data[tmp + 2]) * data[tmp + 3]);
}
energyMap[y].push(Math.sqrt(xSum * xSum + ySum * ySum));
}
}
});
}