-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbenchmark.ts
More file actions
48 lines (41 loc) · 1.29 KB
/
Copy pathbenchmark.ts
File metadata and controls
48 lines (41 loc) · 1.29 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
const pattern = [
[1, 1, 1, 0, 1, 1, 1], // 0
[0, 0, 1, 0, 0, 1, 0], // 1
[1, 0, 1, 1, 1, 0, 1], // 2
[1, 0, 1, 1, 0, 1, 1], // 3
[0, 1, 1, 1, 0, 1, 0], // 4
[1, 1, 0, 1, 0, 1, 1], // 5
[1, 1, 0, 1, 1, 1, 1], // 6
[1, 0, 1, 0, 0, 1, 0], // 7
[1, 1, 1, 1, 1, 1, 1], // 8
[1, 1, 1, 1, 0, 1, 1], // 9
];
// simulate typical puzzle size ~ 15-20 characters
const patterns = Array.from({ length: 20 }, () => pattern[Math.floor(Math.random() * pattern.length)]);
function method1(patterns: number[][]) {
return patterns.flat().reduce((sum, v) => sum + v, 0);
}
function method2(patterns: number[][]) {
let count = 0;
for (let i = 0; i < patterns.length; i++) {
const p = patterns[i];
for (let j = 0; j < p.length; j++) {
count += p[j];
}
}
return count;
}
const iterations = 1_000_000;
const start1 = performance.now();
for (let i = 0; i < iterations; i++) {
method1(patterns);
}
const end1 = performance.now();
const start2 = performance.now();
for (let i = 0; i < iterations; i++) {
method2(patterns);
}
const end2 = performance.now();
console.log(`Method 1 (flat.reduce): ${(end1 - start1).toFixed(2)} ms`);
console.log(`Method 2 (nested loop): ${(end2 - start2).toFixed(2)} ms`);
console.log(`Improvement: ${((end1 - start1) / (end2 - start2)).toFixed(2)}x faster`);