浏览一个问题(Finding the highest number of elements in arrays),我想到了这一点:
什么解决方案最快:
实际问题
我想找到最长的阵列并获得他的长度。
这是数组:
[["667653905", "Johjn", "Smith"], ["500500500", "John", "Smith2", "Another field"], ["12342312", "asd", "asdasd", "fghfgh", "fghfgh"]]
目前我正在使用循环,但如果我有50k这是非常慢的解决方案 阵列:
for(var i = 0; i<explode.length; i++) { console.log(explode[i].length); }
- 第一个回答:
var longest = theArray.reduce(function(lsf, a) {
return !lsf || a.length > lsf.length ? a : lsf;
}, null);
console.log("longest array has " + longest.length + " elements");
- 第二个回答者:
var max = 0;
var explode = new Array();
explode = [["667653905", "Johjn", "Smith"],
["500500500", "John", "Smith2", "Another field"],
["12342312", "asd", "asdasd", "fghfgh", "fghfgh"]];
var explodeSize = explode.length;
for (var i = 0; i<explodeSize; i++) {
if (max < explode[i].length) {
max = explode[i].length;
}
}
console.log(max);
其他人建议对数组进行排序,但我猜测所有类型的排序都是“慢速”#34;在这种情况下。
那么,对于100k +值,哪些解决方案会更快?还有其他更好的解决方案吗?
PS:问题不在于如何做,这是一个假设的问题,而只是分析哪个以及为什么会更快/更好。