Toggle navigation
MeasureThat.net
Create a benchmark
Tools
Feedback
FAQ
Register
Log In
filter-vs-reduce-1
(version: 0)
Comparing performance of:
filter vs reduce
Created:
5 years ago
by:
Guest
Jump to the latest result
Script Preparation code:
function _toConsumableArray(arr) { return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); } function _nonIterableSpread() { throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _iterableToArray(iter) { if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter); } function _arrayWithoutHoles(arr) { if (Array.isArray(arr)) return _arrayLikeToArray(arr); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; } function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; } var words = ['achenium', 'acheniums', 'acquitment', 'acquitments', 'actinometry', 'aeronomic', 'amercing', 'amnesic', 'androecium', 'androeciums', 'anemic', 'anoxemic', 'anthemic', 'anthropometric', 'archegonium', 'arcminute', 'arcminutes', 'axonometric', 'becalming', 'becharming', 'beclamoring', 'breadcrumbing', 'callistemon', 'callistemons', 'camerlingo', 'camerlingos', 'campesino', 'campesinos', 'camphine', 'camphines', 'campiness', 'carmine', 'carmines', 'caromelling', 'centigram', 'centigrams', 'centralism', 'centralisms', 'ceruloplasmin', 'ceruloplasmins', 'chairmen', 'chairwomen', 'chambering', 'chamberings', 'chamfering', 'championed', 'championess', 'charminger', 'charmingest', 'chazzenim', 'chimneyboard', 'chimneyboards', 'chloramine', 'chloramines', 'chlorpromazine', 'chlorpromazines', 'cinema', 'cinemas', 'clambering', 'clampering', 'cnemial', 'coalmine', 'coalminer', 'coalminers', 'coalmines', 'coinmate', 'coinmates', 'columniated', 'combinable', 'combinate', 'comedian', 'comedians', 'companied', 'companies', 'compassioned', 'compassionless', 'compearing', 'compellation', 'compellations', 'compendia', 'complained', 'complainer', 'complainers', 'complexation', 'complexations', 'complexional', 'compressional', 'confirmable', 'conservatism', 'conservatisms', 'conservatorium', 'conservatoriums', 'iceman', 'cinema']; function findAnagrams(word, allWords) { var letters = word.split(''); var charCount = function charCount(chars) { return chars.reduce(function (acc, char) { return _defineProperty({ ...acc }, char, acc[char] ? acc[char] + 1 : 1); }, {}); }; var charCountObj = charCount(letters); console.log(charCountObj); return allWords.reduce(function (acc, w) { var charOfWordCount = charCount(w.split('')); return word.length == w.length && word != w && Object.keys(charCountObj).every(function (key) { return charCountObj[key] == charOfWordCount[key]; }) ? [].concat(_toConsumableArray(acc), [w]) : acc; }, []); }; function countOccurrences(arr) { return arr.reduce(function (acc, str) { return _defineProperty({ ...acc }, str, acc[str] ? acc[str] + 1 : 1); }, {}); }; function hasSameLetterCount(word1, word2) { var word1Count = countOccurrences(word1.split('')); var word2Count = countOccurrences(word2.split('')); return Object.keys(word1Count).length === Object.keys(word2Count).length && Object.keys(word1Count).every(function (letter) { return word1Count[letter] === word2Count[letter]; }); }; function findAnagrams2(word, allWords) { return allWords.filter(function (entry) { return hasSameLetterCount(word, entry); }).filter(function (anagram) { return anagram !== word; }); }; var sumForEach = 0, sumReduce = 0, sumMap = 0, sumFilter = 0, sumFor = 0;
Tests:
filter
console.log(findAnagrams2('cinema', words));
reduce
console.log(findAnagrams('cinema', words));
Rendered benchmark preparation results:
Suite status:
<idle, ready to run>
Run tests (2)
Previous results
Fork
Test case name
Result
filter
reduce
Fastest:
N/A
Slowest:
N/A
Latest run results:
No previous run results
This benchmark does not have any results yet. Be the first one
to run it!
Autogenerated LLM Summary
(model
llama3.2:3b
, generated one year ago):
Let's break down the provided benchmark definition and explain what's being tested, compared, and their pros and cons. **Benchmark Definition** The benchmark consists of two test cases: 1. `filter` 2. `reduce` Both test cases use the `findAnagrams` function to find anagrams of a given word in a large array of words (`words`). The difference between the two test cases is how the function is used: * `filter`: Uses `console.log(findAnagrams2('cinema', words));` * `reduce`: Uses `console.log(findAnagrams('cinema', words));` **findAnagrams** The `findAnagrams` function takes two arguments: a word and an array of words. It returns an array of all the words in the input array that are anagrams of the given word. The implementation uses a few helper functions: * `charCount`: Returns an object with character counts for a given string. * `hasSameLetterCount`: Checks if two strings have the same letter count. **Comparison** The two test cases compare the performance of two different ways to use the `findAnagrams` function: 1. Using `filter`: This approach uses the `filter` method to create a new array with only the anagram words that meet the condition (i.e., they are not equal to the original word). 2. Using `reduce`: This approach uses the `reduce` method to iterate over the array and accumulate the results. **Pros and Cons** Here's a brief summary of the pros and cons of each approach: * **Filter**: + Pros: Can be more efficient for small arrays, as it avoids creating an intermediate array. + Cons: May create multiple intermediate arrays, which can lead to performance issues for large inputs. * **Reduce**: + Pros: Can be more efficient for large inputs, as it only creates a single intermediate array. + Cons: May require more memory and processing power, as it needs to iterate over the entire array. In general, the `reduce` approach is likely to perform better for large inputs due to its efficiency in creating an intermediate array. However, for small arrays or specific use cases, the `filter` approach might be preferred for its simplicity and readability. **Latest Benchmark Result** The latest benchmark result shows that: * `filter`: Takes approximately 534 executions per second on a Chrome Mobile 86 device. * `reduce`: Takes approximately 798 executions per second on a Chrome Mobile 86 device. This suggests that the `reduce` approach is indeed faster for this specific use case, likely due to its efficiency in creating an intermediate array.
Related benchmarks:
Array.prototype.filter vs Lodash without 3
Array.prototype.filter vs Lodash without 4
Filter and Map vs Reduce
for loop filter vs native array.filter
Array.filter vs push
Comments
Confirm delete:
Do you really want to delete benchmark?