node.js:嵌套for循环,字符串操作性能令人沮丧

时间:2014-01-14 06:05:13

标签: javascript string performance node.js

我写了一个脚本从上到下读取一个大字符串,而不是从左到右。当我运行代码时,我的CPU的一个内核钉住@ 100%并且代码永远不会完成。如果我取消注释掉console.log,它会慢慢地将字母吐出来并将所有8个内核固定在100%上,内存使用量会慢慢上升,直到它在我的系统上耗尽所有8GB然后崩溃并出现OOM错误。我显然做了一些可怕的错误。

var haystack = 'SRASBPETHWTWHDZVPOAECJHGNXHRKZXRBMSDYGZGNZBBCOKVPPJKKAQECOLGBFIIKTPVSROCCWWGRWDEQTNFSKEDNFBFKWVEELVTBULWROMGTXSASKCTFJQFDOGRNMZEBLFSCFAFWXZVRGFAZHERUTMOETZZRYNUHSRTHEYIVQDXFNWDDSLSSGPFOMYRHBGKONPIWDTZUBBRAJZGBVUGMVZZTPRAXMLZSXYELKJZWXUYUQIUGGHISZHIGSUQHGHTICVWIJVXMUXOQHPDESKSPRJHQVVTRTNQEVUWKGGQDURAXZWTMYUYIISIOXLTHCISFFSNHZMCGEWMOWCHRQKYNDTDLFWERZLEPRLTNZSPFEDCDESQVMLWMXGCXPMSPTJGSXTXINFADZTBUNDIQWOAIGFKQAJWHINHMZCZVMTJJWGTSGGOIBOZCJGVURJETNXSXWEDUNJPVLPZTDIMSIZGQUJALJYWVLRDYDRWVHZNUNKOLAUPTBMKUNFQYLVQKOQIPPWVNDXENRCVABOTNEKKJPURYNAWAGIZFEHYQMOFICBCQKELTMUYVQPYPZKVBYPTLXRLMYEXGAPRCWDJHQASDQHRGSTIYGMEAWOBLFPSDBGGXFBGIARMGLYOFCZXILLFLCVKCKCXYBTKIYRHLPWXBNGLJYVIZHWPIQSQLHURYRRTBTUBYRMMEQULVVJFKRRZTZVOIKNXPIICBQGFPTETWVPVUKEQOVTCOUARDTAVZFSZWBSTWTQEGLIDKUVMTFRXHOWPPJHCEWMTHJRKXENFENKDMPEYVNEMQRDBGZDIBVYCCFLFMFPSXHHADOZWMMOJKQSY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UBZTRSPNGDLFRBXGMHNEOJCMPFOAPWEPLGRABYLLXDLTERRBKDBVYGQNDYYNCHLWDWWYLLVQBOVIHFJLFVTMKDVINYKKERJKSCZTZEKQSFOSMPNVGSNQSQNDAVQJNNLQHJLBTXPZBXFYRRACYWMCKFORKWGNJCLFIXCIQSPWUWTRLJSICZVKZDAIQTURXNBGDLIREHDLDUCDNDXNSHRCLQLATVPHOZRTIXXIQYEJSARNKOOYIIFVLEGISMMEQNCMAKQLXRQRNEKMGFLCNCJWCTRDMEIFCZVJGTLGWDSTBSEUKVWEIHOHMSZKXUCCVHACKLKQJQSXKUJXPTSHKYRMUADWABQSVKIPFRPTDASYVGJXXMSHFNGRDXIQFGCUGHLKOWXPJETKDWUZHZFKEDYTKZEUUQDIJMWKYUVDYZPTWSHNJDBLZMNOTKGCWFRASJBPQYPTAKPDBFPFLZCEPKPTHTQAQVMMFXUUNEGOJOYRCSBIZZPEREIYMQYMBJIDTYCJAJVIQGHLHVYVLFXRJJWEJJEGVJOYCBVQEVXKEDKLRFSOMXWEKBCHEMLCIVTZXXTJOXHPZAIMBTJBHVSOGNWZBRFABAINEEBPWNYSBENBURPTRCAYWKCQCNZXWKRWVLVTHJWSOBEWANCJSLRWZOBPNITSTYNTVJJZNCNSPCFDQQNAMMQPVPQWTBPSAMWZECDXXCKBBEQKSKLALCZRZCNFDYOXEAYHHKRNF';

for ( var n = 0; n < 64; i += 1) {
    for ( var i = n; i < 124*64;  i += 64) {
        //console.log(haystack[i]);
        var vertical = vertical + i;
    }
}

console.log(vertical);
但是什么?我已经对这个大字符串做了其他(indexOf)操作,同样大的数组和性能也很好。这个嵌套for循环是一件令人讨厌的工作吗?我该怎么写呢?

2 个答案:

答案 0 :(得分:4)

这与字符串无关,你甚至都没有访问它。

你搞砸了你的索引变量,循环永远不会终止。在任何地方你都没有尝试增加n,所以它永远位于0

答案 1 :(得分:0)

第一行你有'我'而不是'n'。这意味着你永远不会离开外循环。

for ( var n = 0; n < 64; n += 1) {}