gpt4 book ai didi

javascript - 使用非常大的 Javascript 数组或对象

转载 作者:行者123 更新时间:2023-11-29 16:15:47 24 4
gpt4 key购买 nike

目前我正在编写一个脚本,我必须在其中存储超过 1,250,000 个对象。我在 jQuery each() 循环中使用 push() 函数,如下所示:

words.push({
"page": pagenumber,
"content": word,
"hpos": $(this).attr("HPOS"),
"vpos": $(this).attr("VPOS"),
"width": $(this).attr("WIDTH"),
"height": $(this).attr("HEIGHT")
});

在 Chrome 中它会很快退出,在 30 到 40 秒之间,但在 Internet Explorer 中它可能需要长达 360 秒。

这是一个加载旧报纸的项目,您可以从这些报纸中搜索文本。报纸在目录中并动态加载。在这个测试中,我使用的是 1926 年 10 月的报纸,包含 308 页和超过 1.250.000 个单词。

是否有更好/更快的方法来实现这一目标?

最佳答案

Is there a better/faster way to achieve this?

是:在服务器上执行,而不是在浏览器中执行。这样做的另一个好处是您可以执行一次并重复使用信息。

但假设由于某种原因这是不可能的:

您可以做的第一件事是停止进行数百万次不必要的函数调用,只需在每个循环中执行 $(this) 一次:

.....each(function () {
var $this = $(this);
words.push({
"page": pagenumber,
"content": word,
"hpos": $this.attr("HPOS"),
"vpos": $this.attr("VPOS"),
"width": $this.attr("WIDTH"),
"height": $this.attr("HEIGHT")
});
});

通常重复这样做没什么大不了的(尽管我无论如何都会避免这样做),但如果你这样做了 25 万次......

如果所有这些属性确实是属性,您可以通过从中间切掉 jQuery 来完全避免调用:

.....each(function () {
words.push({
"page": pagenumber,
"content": word,
"hpos": this.getAttribute("HPOS"),
"vpos": this.getAttribute("VPOS"),
"width": this.getAttribute("WIDTH"),
"height": this.getAttribute("HEIGHT")
});
});

jQuery 的 attr 功能很棒,可以解决各种具有特定属性的跨浏览器问题,但我认为这四个中的任何一个都不需要特殊处理,甚至在 IE 上也不需要,所以你可以直接使用DOM的getAttribute

接下来是一些 JavaScript 引擎执行 push 比分配到数组末尾更慢。这两个语句做同样的事情:

myarray.push(entry);
// and
myarray[myarray.length] = entry;

但其他引擎处理 push 的速度与分配一样快或更快(毕竟,这是一个成熟的优化目标)。因此,您可能会查看 IE 的 push 速度是否更慢,如果是,则改用赋值。

关于javascript - 使用非常大的 Javascript 数组或对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16274307/

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