【发布时间】:2016-01-01 13:01:38
【问题描述】:
我有以下代码:
var Combinatorics = require('js-combinatorics');
var fs = require('fs');
cp = Combinatorics.cartesianProduct(
["4", "@", "/\\", "/-\\", "^", "∂", "λ", "α", "(!", "Z", "α"], ["1²", "2", "?", "P\\", "[\"/_", "l\"/_", "|-", "|2", "|?", "®", "12", "/2", "I2", "|^", "|~", "(r)", "|`", "l2", "Я", "ʁ", "я"], ["#", "(-)", ")-(", "/-/", "4", "<~>", "[-]", "\\-\\", "]-[", "]~[", "{-}", "{=}", "|-|", "|~|", "}{", ":-:", "}-{", "н"], ["!", "'", "1", "[]", "][", "|", "¦", "¡", ":", "]", "ι"], ["&", "3", "€", "£", "ë", "[-", "|=-", "ə", "ε"]
);
for(var index = 0; index < cp.length; ++index) {
//may be not the best idea, but in this way I will add new line to each word when saving them into array
var aux = cp.toArray()[index] + '\n';
console.log(cp.toArray()[index])
var contents = fs.appendFile("./output.txt", aux,
function(error) {
if(error) {
console.log("error writing");
}
});
}
它将生成411642个单词并将它们从新行“\n”保存到output.txt中
如果我生成的单词数量不多,此代码运行速度很快,但在我的情况下,要生成 411642 个单词,我使用 output.txt 中的“\n”从换行符编写它们。我使用此代码的速度约为 82 个字/1 分钟。它超级慢。我不明白为什么?我怎样才能让它更快?
【问题讨论】:
-
欢迎来到组合数学的世界。您生成了一个呈指数增长的结果集。 Javascript 不是最快的语言。
-
@EricJ。那么我可以在这里使用什么最简单、最快速的方式来获取我的单词表)?
-
如果您正在使用 console.log 运行循环,请将其删除,它会使其更快。
-
不知道为什么会有这么多反对票,这是一个写得很好的问题,而且很清楚 OP 想要什么......
-
@dandavis this console.log console.log(cp.toArray()[index]) ,不是 appendFile 回调中的那个
标签: javascript node.js performance for-loop