DB
and sort-stream
are fine solutions, but DB might be an overkill and I think sort-stream
eventually just sorts the entire file in an in-memory array (on through
end callback), so I think performance will be roughly the same, comparing to the original solution.
(but I haven't ran any benchmarks, so I might be wrong).
因此,为了解决这个问题,我将提出另一个解决方案:)
EDIT:我很好奇这会有多大的差异,所以我运行了一些基准测试。
事实证明,结果甚至让我感到惊讶sort -k3,3
到目前为止,解决方案更好,速度快了 10 倍然后是原始解决方案(简单的数组排序),而nedb
and sort-stream
解决方案至少慢 x18 倍比原始解决方案慢(即至少慢 x180 倍)sort -k3,3
).
(参见下面的基准测试结果)
如果在 *nix 机器(Unix、Linux、Mac...)上,您可以简单地使用
sort -k 3,3 yourInputFile > op_rev.txt
并让操作系统为您进行排序。
您可能会获得更好的性能,因为排序是本机完成的。
或者,如果您想在 Node 中处理排序后的输出:
var util = require('util'),
spawn = require('child_process').spawn,
sort = spawn('sort', ['-k3,3', './test.tsv']);
sort.stdout.on('data', function (data) {
// process data
data.toString()
.split('\n')
.map(line => line.split("\t"))
.forEach(record => console.info(`Record: ${record}`));
});
sort.on('exit', function (code) {
if (code) {
// handle error
}
console.log('Done');
});
// optional
sort.stderr.on('data', function (data) {
// handle error...
console.log('stderr: ' + data);
});
希望这可以帮助 :)
EDIT:添加一些基准细节。
我很好奇这会有多大的差异,所以我运行了一些基准测试。
以下是结果(在 MacBook Pro 上运行):
sort1 https://gist.github.com/yoava/fd291e13ef703a4ea68a33c463dc376a使用一种简单的方法,对记录进行排序in-memory array
.
平均时间:35.6s(基线)
sort2 https://gist.github.com/yoava/7d45c531cf727247c393d43d6033a938 uses sort-stream
,正如乔·克里尔建议的那样。
平均时间:11.1m (about 慢 18.7 倍)
(我想知道为什么。我没有深入研究。)
sort3 https://gist.github.com/yoava/8a05ad916efb852cfd0f2b3482d7ec0c uses nedb
,正如 Tamas Hegedus 所建议的那样。
时间:约16m (about 慢 27 倍)
sort4 https://gist.github.com/yoava/78a6f880db73ee4686162caed88a459d仅通过执行来排序sort -k 3,3 input.txt > out4.txt
在终端中
平均时间:1.2s (about 快 30 倍)
sort5 https://gist.github.com/yoava/579fe6953a22ca724ed3afd95929f389 uses sort -k3,3
,并处理发送到标准输出的响应
平均时间:3.65s (about 速度提高 9.7 倍)