summaryrefslogtreecommitdiff
path: root/benchmark/find.js
blob: cc95a44481dbd44511eb5ecd0001f08a015bb248 (plain)
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const products = require('../data/products.json');
var microtime = require('microtime');


var selected = [];
products.forEach( pr => {
    if (Math.floor(Math.random() * 100) > 85) {
        selected.push(pr.id);
    }
});


function compare() {

    var f0 = microtime.nowDouble();
    for(i=0 ; i < 4 ; i++) byFor();
    var f1 = microtime.nowDouble();
    // 
    var e0 = microtime.nowDouble();
    for(i=0 ; i < 4 ; i++) byEach();
    var e1 = microtime.nowDouble();
    //
    var b0 = microtime.nowDouble();
    for(i=0 ; i < 4 ; i++) byFind();
    var b1 = microtime.nowDouble();

    return {
        for: f1-f0,
        ifor: byFor(),
        each: e1-e0,
        ieach: byEach(),
        find: b1-b0,
        ifind: byFind(),
        sel: selected,
    }
}


function byFor() {
    var items = [];
    var notFound = [];
    var found;
    selected.forEach( id => {
        found = false;
        for(i = 0; i < products.length; i++) {
            if (products[i].id == id) {
                items.push(products[i]);
                found = true;
                break;
            }
        }
        if (!found) notFound.push(id)

    })
    return {items: items, nf: notFound};
}


function byEach() {
    var items = [];
    var notFound = [];
    var found;
    selected.forEach( id => {
        found = false;
        products.forEach( pr => {
            if (pr.id == id) {
                items.push(pr);
                found = true;
            }
        });
        if (!found) notFound.push(id)
    });
    return {items: items, nf: notFound};
}

function byFind() {
    var items = [];
    var notFound = [];
    var result;
    selected.forEach( id => {
        found = false;
        result = products.find((pr) => pr.id == id);
        if (result === undefined) notFound.push(id)
        else items.push(result);
    });
    return {items: items, nf: notFound};
}

module.exports = {
    compare,
    byFor
}