So what is the difference between this two functions?
They both create new Array
object. Only difference I found so far is that Array.from
supp
Static method vs instance method
I know a lot of time has passed since the question was asked. A lot of good things have been said. But I would like to add some more. If we try to determine the nature of the two methods we can say that Array.from has no relation to any instance of Array. It is static method like Array.isArray or Array.of. You also have static properties like length for the Array object. As a static method Array.from can not be Called from instance. For example:
var indexes=[0,1,2,3]
index.from()
>>> index.from is not a function
In the other hand if you write
Array.map()
you will end up with a Array.map is not a function
. It is because Array.prototype.map Exist for the instance of array. In our little example indexes is an instance of Array then we use map on it.
Example
var indexes=[0,1,2,3]
function doubleIt(x){
return 2*x;
}
indexes.map(doubleIt);
With array.from it shoud be something like
Array.from(indexes, doubleIt)
I used quokka plugin on vscode to evaluate performance on vs code in a windows machine. It is not real case of performance benchmarking. But it can help to have an idea. I came up with the same conclusion as @rileynet map seem more performant but only for large array.
var N=10
var tabIndex=[ ...Array(N).keys()]
function doubleIt(x){
return 2*x;
}
tabIndex.map(doubleIt);/*?.*/ 0.040ms
Array.from(tabIndex, doubleIt)/*?.*/ 0.009ms
if N=100
tabIndex.map(doubleIt);/*?.*/ 0.052ms
Array.from(tabIndex, doubleIt)/*?.*/ 0.041ms
if N=1000
tabIndex.map(doubleIt);/*?.*/ 0.228ms
Array.from(tabIndex, doubleIt)/*?.*/ 0.339ms
if N=10000
tabIndex.map(doubleIt);/*?.*/ 2.662ms
Array.from(tabIndex, doubleIt)/*?.*/ 1.847ms
N=100000
tabIndex.map(doubleIt);/*?.*/ 3.538ms
Array.from(tabIndex, doubleIt)/*?.*/ 11.742ms