Skip to content

Commit 897518a

Browse files
authoredJun 3, 2022
Improve performance (#14)
1 parent 6a82db0 commit 897518a

File tree

2 files changed

+34
-1
lines changed

2 files changed

+34
-1
lines changed
 

‎benchmark.js

+31
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
import filterObj from 'filter-obj';
2+
3+
// Benchmark `filter-obj`.
4+
// Higher `loopCount` give more precise results but last longer.
5+
// `objectSize` gives different results based on how big the input object is.
6+
// `predicateSize` is similar but for predicate arrays. When `undefined`, a predicate function is used instead.
7+
const benchmark = function (loopCount, objectSize, predicateSize) {
8+
const bigObject = Object.fromEntries(Array.from({length: objectSize}, getObjectKeyPair));
9+
const predicate = predicateSize === undefined ? isEven : Array.from({length: predicateSize}, getPredicateKey);
10+
11+
console.time();
12+
for (let index = 0; index < loopCount; index += 1) {
13+
filterObj(bigObject, predicate);
14+
}
15+
16+
console.timeEnd();
17+
};
18+
19+
const getObjectKeyPair = function (_, index) {
20+
return [`a${index}`, index];
21+
};
22+
23+
const getPredicateKey = function (_, index) {
24+
return `a${index}`;
25+
};
26+
27+
const isEven = function (key, value) {
28+
return value % 2 === 0;
29+
};
30+
31+
benchmark(1e3, 1e4);

‎index.js

+3-1
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,9 @@ export default function filterObject(object, predicate) {
1515
}
1616
}
1717
} else {
18-
for (const [key, value] of Object.entries(object)) {
18+
// `for ... of Object.keys()` is faster than `for ... of Object.entries()`.
19+
for (const key of Object.keys(object)) {
20+
const value = object[key];
1921
if (predicate(key, value, object)) {
2022
Object.defineProperty(result, key, {
2123
value,

0 commit comments

Comments
 (0)
Please sign in to comment.