gpt4 book ai didi

javascript - 为什么这段代码这么慢?

转载 作者:行者123 更新时间:2023-12-03 16:33:55 25 4
gpt4 key购买 nike

jsc.tools.road.correctType = function() {
for(row = jsc.data.selection.startX - 1; row <= jsc.data.selection.endX + 1; row++) {
for(col = jsc.data.selection.startY - 1; col <= jsc.data.selection.endY + 1; col++) {
if(jsc.data.cells[row-1][col].type != "road" && jsc.data.cells[row+1][col].type != "road" && jsc.data.cells[row][col].type == "road") {
jsc.ui.addClassToCell("horz", row, col);
}
else {
jsc.ui.removeClassFromCell("horz", row, col);
}
if(jsc.data.cells[row][col-1].type != "road" && jsc.data.cells[row][col+1].type != "road" && jsc.data.cells[row][col].type == "road") {
jsc.ui.addClassToCell("vert", row, col);
}
else {
jsc.ui.removeClassFromCell("vert", row, col);
}
}
}
};

// Elsewhere
jsc.ui.addClassToCell = function(class, x, y) {
$("#" + x + "-" + y).addClass(class);
};
jsc.ui.removeClassFromCell = function(class, x, y) {
$("#" + x + "-" + y).removeClass(class);
};

上面的代码运行很慢。我不知道为什么。它使用 jQuery 1.3.2。有什么办法可以稍微优化一下吗?

编辑:该代码是我作为个人项目制作的 javascript 游戏的一部分。它基本上是模拟城市的克隆。这段代码检查道路每一部分的相邻单元格,并将类别(以及背景图像)更改为正确的类别,以使道路图像正确排列,例如水平、垂直和交叉路口(无类别)道路图像。

编辑 2:提供一些上下文的更多细节。

jsc.data.cells 是一个 200 x 200 的数组。每个数组元素都是一个具有如下属性的对象(默认显示):{type: null, developed: false, powered: false, watered: false, hasTransport: false, wealth: 0, quality: 0}。

它的对应物在 UI 中,它基本上是一个巨大的表格。 (又是 200 x 200)。在整个程序中,每个单元格都添加了许多 CSS 类以更改背景图像(例如 .road 将其更改为道路,.com.developed 使其成为发达的商业区)。每个表格单元格都有一个 #x-y 形式的 ID,这是 jsc.ui.addClassToCell 和 jsc.ui.removeClassFromCell 编辑的内容。

编辑 3:修复了以数字开头的 ID。现在尝试一些优化。

最佳答案

使用 O() 表示法的简短估计:

for(row) ... O(N)
for(col) ... O(N)
$().addClass/removeClass ... O(N^2)

$() 在嵌套的 for 中甚至被调用了两次。

所以你最终得到 O(N^4)

您可以通过在 jsc.data.cells[row][col] 的 as 属性中缓存计算的类来优化这一点,例如

jsc.data.cells[row][col].horz = 1; // don't set class "horz" if not present
jsc.data.cells[row][col].vert = 1;

并在 HTML 表格内创建单元格时使用缓存的数据,而不是为每个单元格调用 $()。

关于javascript - 为什么这段代码这么慢?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/845073/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com