Javascript 算法性能:JS函数的解分析
你好!我对算法性能分析(大O时间和空间复杂度)不太了解,我想知道我写的代码是否具有适当的时间和空间复杂度。还有什么方法可以提高复杂性吗 下面是两个功能。第一个方法获取一个数组并运行两个Javascript 算法性能:JS函数的解分析,javascript,algorithm,performance,html5-canvas,Javascript,Algorithm,Performance,Html5 Canvas,你好!我对算法性能分析(大O时间和空间复杂度)不太了解,我想知道我写的代码是否具有适当的时间和空间复杂度。还有什么方法可以提高复杂性吗 下面是两个功能。第一个方法获取一个数组并运行两个forEacharray-helper方法。其目的是正确移动屏幕上的线条。第二个是 函数1-时间复杂度-O(N^2),空间复杂度-O(N)…是否正确 self.penciledLines.forEach((arr, index) => { arr.forEach((line) =>
forEach
array-helper方法。其目的是正确移动屏幕上的线条。第二个是
函数1-时间复杂度-O(N^2),空间复杂度-O(N)…是否正确
self.penciledLines.forEach((arr, index) => {
arr.forEach((line) => {
if (index === self.selectedArrayLinesIndex) {
if (
line.x1 + xDiff <= 0
|| line.y1 + yDiff <= 0
|| line.x1 + xDiff >= 800
|| line.y1 + yDiff >= 600
|| (line.x2 + xDiff <= 0
|| line.y2 + yDiff <= 0
|| line.x2 + xDiff >= 800
|| line.y2 + yDiff >= 600)
) {
const alerted = localStorage.getItem('alerted') || '';
if (alerted !== 'yes') {
alert("On No! You can't move beyond the drawing canvas");
localStorage.setItem('alerted', 'yes');
}
setTimeout(() => {
localStorage.removeItem('alerted');
}, 1000);
self.mouseIsDown = false;
return;
}
line.move(xDiff, yDiff);
self.pos = [mouseX, mouseY];
}
});
});
感谢您抽出时间,我只是想确保我了解如何进行分析。还有一些方法可以改善这种情况吗?从另一个角度来看: double for循环的内部是一小部分内容
line.move
可能是最昂贵的(在速度上)——但这是你无法控制的var x = min(x1, x2) + xdiff;
var y = min(y1, y2) + ydiff;
if ( x < 0 || x > 800 ||
y < 0 || y > 600 )
var x=min(x1,x2)+xdiff;
变量y=最小值(y1,y2)+ydiff;
如果(x<0 | | x>800||
y<0 | | y>600)
代码空间相似;速度快得多
现在,从另一个角度来看。。。目标是什么?移动屏幕上的一组线直到任何一条线碰到边缘?如果这是你的重点,那么考虑这个方法:
与其使用二维阵列,不如将其视为一维线阵列。我看不到任何依赖2D的东西。如果你说的是教科书式的大O,这意味着最坏的情况,你无法改进它。但从实际角度看,是的,这是可以做到的。如果有条件,您可以更改
的位置
(index === self.selectedArrayLinesIndex) // from first function
与每个
之前的中的匿名函数中的任何逻辑完全无关。如果它不满足该条件,则根本不需要循环
if (index === self.selectedArrayLinesIndex) {
arr.forEach((line) => { // swapped positions
根据名字,我很确定line.move(xDiff,yDiff)
是你真正的瓶颈
此外,如果你想分清界限,
for
循环比之前的更快
不确定,但这可能倾向于CodeReview?是的,你的分析是正确的,不,你不能真正优化它。太好了!感谢您的回复if(index==self.selectedArraylineIndex)
应该指出一个明显的优化潜力…这是一个非常好的解释,让我确信。我很感激!
if (index === self.selectedArrayLinesIndex) {
arr.forEach((line) => { // swapped positions