如何更快地索引 Javascript 中的对象数组?
为了构建 JQuery 自动完成所需的字符串数组,我遍历一个对象数组并将其展平为唯一字符串数组。我这样做的方式符合您的预期:
var input = [{prop1:'value1', prop2: 'value2'}];
$.each(input, function (index, value) {
$.each(value, function (i, v) {
if (v != undefined && v != null && v != '' && ($.inArray(v, keywords) < 0)) {
keywords.push(v);
}
});
});
问题是它对于大型输入集表现不佳,并且在运行时会阻塞 UI。我怎样才能让这个变得更好?
In order to build the array of strings necessary for JQuery autocomplete, I'm traversing an array of objects and flattening it into an array of unique strings. I'm doing this about how you might expect:
var input = [{prop1:'value1', prop2: 'value2'}];
$.each(input, function (index, value) {
$.each(value, function (i, v) {
if (v != undefined && v != null && v != '' && ($.inArray(v, keywords) < 0)) {
keywords.push(v);
}
});
});
The problem is that it performs poorly for large input
sets, and blocks the UI while it's running. How can I make this better?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你有一个 O(n^2) 算法。一遍又一遍地查看关键字数组会变得非常慢(正如您所注意到的)。
相反,将关键字保留为对象:
请注意,可以通过让 JavaScript 检查其真实性来替换对“v”对未定义、null 和空字符串的测试。这并不总是正确的事情,但在这里没问题。
如果您愿意,您还可以将关键字保存在数组中。只是不要搜索数组来确定是否已经看到关键字。
You've got an O(n^2) algorithm there. Looking through that keywords array over and over again is going to get really slow (as you've noticed).
Instead, keep the keywords as an object:
Note that your tests of "v" against undefined, null, and the empty string can be replaced by letting JavaScript check it's truthiness. That's not always the right thing, but it's fine here.
You can also keep the keywords in an array, if you like. Just don't search the array to determine whether a keyword has been seen yet.
我认为你正在尝试解决错误的问题,
为什么你的自动建议列表如此之大以至于 javascript 表现不佳?只需将前 10 条自动建议发送给客户就可以了
i think you're trying to fix wrong problem
why is your autosuggestion list so big that javascript performs poorly? just send top 10 autosuggestions to client and you'll be fine