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

Wez*_*ezy 2 javascript optimization performance jquery

目前我正在编写一个脚本,我必须存储超过1,250,000个对象.我push()在这样的jQuery each()循环中使用该函数:

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

在Chrome中它会快速退出,在30到40秒之间,但在Internet Explorer中最多可能需要360秒.

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

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

T.J*_*der 6

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

是:在服务器上进行,而不是在浏览器中进行.这也有一个好处,你可以做一次并重用信息.

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

你可以做的第一件事就是停止进行数百万个不必要的函数调用,每个循环只执行$(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")
    });
});
Run Code Online (Sandbox Code Playgroud)

通常反复这样做并不是什么大问题(尽管我还是会避免它),但如果你这样做了一次又一次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")
    });
});
Run Code Online (Sandbox Code Playgroud)

jQuery的attr功能非常好,可以平滑各种具有某些属性的跨浏览器麻烦,但我不认为这四种中的任何一种都需要特殊处理,甚至在IE上都不需要,所以你可以直接使用DOM getAttribute.

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

myarray.push(entry);
// and
myarray[myarray.length] = entry;
Run Code Online (Sandbox Code Playgroud)

但是其他引擎的处理push速度比分配快(或者更快)(毕竟,它是一个成熟的优化目标).所以你可能会看看IE是否做得push更慢,如果是这样,转而使用赋值.