我刚在jsperf上运行了这个基准测试:https://jsperf.com/mapping1
我试图看看使用递归的map函数是否能击败
Array.prototype
的map函数。结果我的代码输了。请问有人可以解释为什么吗?map = function(f, xs) {
if (xs.length === 0) {return []}
return [f(head(xs))].concat(map(f, tail(xs)))
}
// head() and tail() do exactly what you would expect. I wish there was a way to programmatically fork lists in js...
.concat()
创建一个新数组。 - robertklepArray.prototype.map()
也是这样的吧? - dopatraman[<elem>]
相同。你可能也在对数组进行头尾切片,而map则会原地对数组进行操作,并将聚合的输出放入一个新的单一数组中。 - Patrick MArray::map
只创建一个新数组。而你的函数在每个递归步骤中都会创建 3 个新数组。 - Bergi