<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.29/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.2/lodash.min.js"></script>
<script>
_lodash = _.noConflict();
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
var angularFilter = angular.injector(['ng']).get('$filter')('filter');
// Generate test array
window.array = (function() {
var arr = [];
for (var i = 0; i < 100; ++i) {
arr.push(i);
}
return arr;
}());
Array.prototype.find = function(predicate) {
if (this == null) {
throw new TypeError('Array.prototype.find called on null or undefined');
}
if (typeof predicate !== 'function') {
throw new TypeError('predicate must be a function');
}
var list = Object(this);
var length = list.length >>> 0;
var thisArg = arguments[1];
var value;
for (var i = 0; i < length; i++) {
value = list[i];
if (predicate.call(thisArg, value, i, list)) {
return value;
}
}
return undefined;
};
function getValue(el) {
return el - 50 > 31;
}
array.find(getValue);
array.filter(getValue);
_lodash.filter(array, getValue);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
array.find | |
array.filter | |
lodash.filter |
Test name | Executions per second |
---|---|
array.find | 1909553.6 Ops/sec |
array.filter | 2054623.8 Ops/sec |
lodash.filter | 1294219.4 Ops/sec |
Measuring the performance of JavaScript functions can be a complex task, as it depends on various factors such as browser, device platform, operating system, and hardware capabilities.
Benchmark Definition
The provided JSON defines two microbenchmarks: array.find
and array.filter
. Both benchmarks test the execution speed of the getValue
function, which is applied to an array using these methods.
getValue
). If no such element is found, it returns undefined.getValue
).Options Compared
The benchmark compares three approaches:
filter
method.Pros and Cons
Other Considerations
getValue
function is a simple predicate that subtracts 50 from each element and checks if the result is greater than 31. This might not be a realistic use case for most developers.Other Alternatives
If you're looking for alternative methods to implement filter
or find
, consider the following:
Array.prototype.map
and then filtering the resulting array.Keep in mind that these alternatives might not be as efficient or reliable as the native methods provided by modern browsers.