-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathloop.js
65 lines (56 loc) · 1.71 KB
/
loop.js
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
const arr = [
'test', 'hello', 'hu', 'test to my', 'welcome', 'hu', 'test to test', 'morning', 'hi', 'tu', 'yes', 'no', 'test', 'hello', 'test', 'hello', 'hu',
'morning', 'hi', 'tu', 'yes', 'no', 'test', 'hello', 'test', 'hello', 'hu', 'morning', 'hi', 'tu', 'yes', 'no', 'test', 'hello', 'test', 'hello', 'hu',
'morning', 'hi', 'tu', 'yes', 'no', 'test', 'hello', 'morning', 'hi', 'tu', 'yes', 'no', 'test', 'hello',
'morning', 'hi', 'tu', 'yes', 'no', 'test', 'hello', 'morning', 'hi', 'tu', 'yes', 'no', 'test', 'hello'
];
// Use performance now
const t0 = performance.now();
const loopUsingForUsePerformance = input => {
let output = [];
for (let i = 0; i < input.length; i++) {
output.push(input[i].toUpperCase());
}
return output;
};
const t1 = performance.now();
loopUsingForUsePerformance(arr)
console.log(t0, 'milliseconds');
console.log(t1, 'milliseconds');
console.log(t1 - t0, 'milliseconds');
// Use time
console.time('test')
const loopUsingForUseTime = input => {
let output = [];
for (let i = 0; i < input.length; i++) {
output.push(input[i].toUpperCase());
}
return output;
};
loopUsingForUseTime(arr);
console.timeEnd('test')
// Use forEach method
function testForEach(arr) {
console.time('test-forEach');
const result = [];
arr.forEach((val, index) => {
result.push(val / 1.2 * 0.1);
});
console.timeEnd('test-forEach');
return result;
}
// Use for
function testFor(arr) {
console.time('test-fo');
// test if len define
const len = arr.length;
const result = [];
for (let i = 0; i < len; i++) {
result.push(arr[i] / 1.2 * 0.1);
}
console.timeEnd('test-forEach');
return result;
}
const arr1 = Array(100).fill(Math.random());
testForEach(arr1);
testFor(arr1)