Reputation: 14737
I was just reading this answer regarding hashing in Javascript, and, while it was definitely faster than the accepted answer, it requires the reduce
function on the Array
prototype.
Checking the existence of the reduce
function is easy enough; but while most checks I do (and have seen) check against the prototype, it just made me wonder: what are the implications of checking against an instance itself? Why does the prototype check seem to be preferred?
// i.e.
if (!!Array.prototype.reduce) { }
// vs
if (!![].reduce)
The instance will definitely need an instance, so that's one thing, but is that it?
Upvotes: 3
Views: 88
Reputation:
Just ran a benchmark: http://jsperf.com/prototype-vs-instance-property-check
Array.prototype.reduce
is 3x faster due to the instantiation of an empty array, but realistically, there is absolutely no difference since these checks are almost always one-time checks, and not in code that runs all the time.
I personally have reduced this to [].method
for years. I do the same for things like Array.prototype.slice.call( .. )
vs [].slice.call( ... )
, and those are called far more often than once.
But note that this is only valid on Array
, so you're really not saving a lot.
Upvotes: 3
Reputation: 239402
The second version involves needlessly instantiating an empty array. Why do so, when you can just ask the prototype itself and not instantiate anything?
Upvotes: 2