Toggle navigation
MeasureThat.net
Create a benchmark
Tools
Feedback
FAQ
Register
Log In
js Count the occurences of an item in an array
(version: 6)
Comparing performance of:
arr.filter vs for vs arr.reduce vs regex vs indexOf
Created:
9 years ago
by:
Registered User
Jump to the latest result
Tests:
arr.filter
count = function(arr, item) { return arr.filter(function(x){return x==item}).length } count([1,2,3,2,4,2], 2);
for
count = function(arr, item) { var count = 0; for(var i = 0; i < arr.length; ++i){ if(arr[i] == item) count++; } return count } count([1,2,3,2,4,2], 2);
arr.reduce
count = function(arr, item) { return arr.reduce(function(total,x){return x==item ? total+1 : total}, 0); } count([1,2,3,2,4,2], 2);
regex
count = function(arr, item) { var regex = new RegExp('[^'+item+']+', 'g'); return String(arr).replace(regex,'').length } count([1,2,3,2,4,2], 3);
indexOf
count = function(arr, item) { var count= 0, i; while((i= arr.indexOf(item, i))!= -1){ ++count; ++i; } return count; } count([1,2,3,2,4,2], 2);
Rendered benchmark preparation results:
Suite status:
<idle, ready to run>
Run tests (5)
Previous results
Fork
Test case name
Result
arr.filter
for
arr.reduce
regex
indexOf
Fastest:
N/A
Slowest:
N/A
Latest run results:
Run details:
(Test run date:
one year ago
)
User agent:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36
Browser/OS:
Chrome 131 on Mac OS X 10.15.7
View result in a separate tab
Embed
Embed Benchmark Result
Test name
Executions per second
arr.filter
10780288.0 Ops/sec
for
11988019.0 Ops/sec
arr.reduce
12155319.0 Ops/sec
regex
2858277.5 Ops/sec
indexOf
9523024.0 Ops/sec
Autogenerated LLM Summary
(model
llama3.2:3b
, generated one year ago):
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net. **Benchmark Definition** The benchmark definition provides a brief description of what is being measured: counting the occurrences of an item in an array. The script preparation code and HTML preparation code are empty, indicating that these steps do not need to be executed before running the benchmarks. **Individual Test Cases** There are four test cases: 1. **arr.filter**: This test case uses the `filter()` method to create a new array with only the elements that pass the test implemented by the provided function. 2. **for**: This test case uses a traditional `for` loop to iterate through the array and count the occurrences of the item. 3. **arr.reduce**: This test case uses the `reduce()` method to apply a binary function (in this case, incrementing a counter) to an accumulator value (the current element being processed) across all elements in the array. 4. **regex**: This test case uses regular expressions to search for the item in the string representation of the array and count the matches. 5. **indexOf**: This test case uses the `indexOf()` method to find the index of the first occurrence of the item in the array, then increments a counter for each subsequent match. **Options Compared** Each test case is comparing a different approach to counting occurrences: * `arr.filter` vs. `for`: The `filter()` method is often faster than a traditional `for` loop because it avoids the overhead of incrementing a counter. * `arr.reduce` vs. `for`: The `reduce()` method can be more efficient than a traditional `for` loop because it allows for accumulation and iteration in a single pass. * `regex` vs. `indexOf`: Regular expressions are often slower than using `indexOf()` because they require the browser's regex engine to execute. **Pros and Cons** Here's a brief summary of the pros and cons of each approach: * **arr.filter**: Pros: fast, efficient; Cons: requires creating a new array, can be slow for large inputs. * **for**: Pros: straightforward, easy to understand; Cons: slow due to counter incrementation. * **arr.reduce**: Pros: efficient accumulation, single pass through the array; Cons: may require more complex implementation. * **regex**: Pros: flexible pattern matching; Cons: slow due to regex engine overhead. * **indexOf**: Pros: fast, efficient; Cons: limited to finding a single match. **Library Usage** None of the test cases use an external library (e.g., jQuery). **Special JS Features or Syntax** None of the test cases employ special JavaScript features or syntax (e.g., `let`, `const`, arrow functions). However, some might use modern JavaScript features not supported in older browsers. **Alternatives** Some alternative approaches to counting occurrences could be: * Using an array-based solution with a single pass through the array. * Utilizing native browser methods like `Array.prototype.some()` or `Array.prototype.every()`. * Leveraging external libraries like Lodash or Underscore.js for more efficient filtering and mapping. Keep in mind that each approach has its strengths and weaknesses, and the best choice depends on specific requirements and performance constraints.
Related benchmarks:
unique elements in array using filter v2.3
unique elements in array using filter - large array
count the number of occurrences in array
test js count
Comments
Confirm delete:
Do you really want to delete benchmark?