简体   繁体   English

如何在合并,排序javascript数组时提高性能

[英]how to improve performance on merging, sorting javascript arrays

I have two arrays. 我有两个数组。 One is sorted, the other is not. 一个是排序的,另一个不是。

The sorted array is pretty big, let's say 90,000 entries. 排序后的数组很大,可以说有90,000个条目。 The second array will be short - currently no more than 401. 第二个数组将很短-当前不超过401。

The problem is that I load a file, and read that file to determine values to put in to the short array, when I am done with that file the short array has to be merged with the sorted array and serialized to disk. 问题是我加载了一个文件,然后读取该文件以确定要放入短数组中的值,当我处理完该文件时,短数组必须与已排序的数组合并并序列化到磁盘。 I do the merge and sort as you would expect: 我按照您的期望进行合并和排序:

var hashes = [
"M2E0Mzk3YmItOWUzMC00ZmMwLWFhZDQtYTA0NTk0YWIwYjhjXw==mtg0mtq3nze2nw",
"M2ExZjNmNDktODdhOS00ODJiLTg2NzQtM2NiODQ1Njc1ZmYzXw==lte0mzg2otgxmdk",
"M2EzNTExM2UtY2JmYS00ZjAzLTgwZmMtMjg4ZDJkZjA5YzJjXw==mtcxmjqxmdc1mq",
"M2EzZjkzZDQtODUwYS00ZjlkLTg3ZmQtZjliNTFjZmYxNjVhXw==mjgzodu3nji3" ];

var append_to_hashes = [
"M2E2NGZjNWEtMzkwYy00YzE4LTkzM2EtNDVmNjE1MjE2ZDViXw==ltcxmzk1otawng",
"M2ExZjE2NGItNzUwZi00YTU4LWI3OGMtZDVkNDA2YWE2MzRmXw==ltq3odgznja2op",
"M2ExZjE2NGItNzUwZi00YTU4LWI3OGMtZDVkNDA2YWE2MzRmXw==ltq3odgznja2oa"];

if(append_to_hashes.length > 0){
   hashes = hashes.concat(append_to_hashes);
   hashes = hashes.sort();
}

But I'm wondering if there is a more performant way to concatenate and sort the arrays. 但是我想知道是否有更高性能的方法来连接和排序数组。

You can sort the smaller array and then insert each item in proper place: 您可以对较小的数组进行排序,然后将每个项目插入适当的位置:

var big = [...]; // Big sorted array
var small = [...];  // Small unsorted array

small.sort();

for(let i = 0; i < big.length && small.length > 0; i++) {
    if(big[i].localeCompare(small[0]) > 0) {
        big.splice(i, 0, small.shift());
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM