-
Notifications
You must be signed in to change notification settings - Fork 29
/
map_loop.js
56 lines (52 loc) · 1.07 KB
/
map_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
var _ = require("lodash");
var arr = _.range(100000);
function plusOne(num) {
return num + 1;
}
const cases = [
{
name: "normal loop. use push",
fn: function () {
var result = [];
for (var i = 0; i < arr.length; i++) {
result.push(plusOne(arr[i]));
}
},
},
{
name: "normal loop. use index",
fn: function () {
var result = [];
for (var i = 0; i < arr.length; i++) {
result[i] = plusOne(arr[i]);
}
},
},
{
name: "new Array(arr.length)",
fn: function () {
// avoid dynamic memory alloc when array grows
var result = new Array(arr.length);
for (var i = 0; i < arr.length; i++) {
result[i] = plusOne(arr[i]);
}
},
},
{
name: "native map",
fn: function () {
var result = arr.map(function (item) {
return plusOne(item);
});
},
},
{
name: "lodash.forEach",
fn: function () {
var result = _.map(arr, function (item) {
return plusOne(item);
});
},
},
];
exports = module.exports = { cases };