UNPKG

2.93 kBJavaScriptView Raw
1var Datastore = require('nedb'),
2 ndb = new Datastore(),
3 samplecoll = null,
4 arraySize = 10000, // how large of a dataset to generate
5 totalIterations = 200, // how many times we search it
6 results = [],
7 gAsyncCount = 0,
8 startTime,
9 endTime,
10 isIndexed = false;;
11
12// not really using right now, if we need to time each op independently i might use this outside timing logic
13function genRandomVal()
14{
15 var text = "";
16 var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
17
18 for( var i=0; i < 20; i++ )
19 text += possible.charAt(Math.floor(Math.random() * possible.length));
20
21 return text;
22}
23
24function initializeDB() {
25 gAsyncCount = 0;
26
27 startTime = process.hrtime();
28
29 // nedb uses async callbacks so we will not time each operation but
30 // use globals to count when the last async op has finished
31 for (var idx=0; idx < arraySize; idx++) {
32 var v1 = '12345'; //genRandomVal();
33 var v2 = '23456'; //genRandomVal();
34
35 ndb.insert({
36 customId: idx,
37 val: v1,
38 val2: v2,
39 val3: "more data 1234567890"
40 }, function (err, newDoc) { // Callback is optional
41 if (++gAsyncCount == arraySize) {
42 endTime = process.hrtime(startTime);
43 var totalMS = endTime[0] * 1e3 + endTime[1] / 1e6;
44 var rate = arraySize * 1000 / totalMS;
45 rate = rate.toFixed(2);
46 console.log("load (insert) : " + totalMS + "ms (" + rate + ") ops/s");
47
48 testperfFind();
49 }
50 });
51 }
52}
53
54// benchmark find() performance
55// called by initializedb once its last async insert is complete
56// This test runs once unindexed and on completion of all async ops it will add an index and run again
57 function testperfFind() {
58 var loopIterations = totalIterations;
59
60 // if running indexed, the test will complete alot faster.
61 // Using a multiplier so that the test takes close to 1 second for more accurate rate calculation.
62 if (isIndexed) {
63 loopIterations = loopIterations * 200;
64 }
65
66 gAsyncCount = 0;
67
68 startTime = process.hrtime();
69
70 for (var idx=0; idx < loopIterations; idx++) {
71 var customidx = Math.floor(Math.random() * arraySize) + 1;
72
73 ndb.find({ customId: customidx }, function (err, docs) {
74 ++gAsyncCount;
75
76 if ((!isIndexed && gAsyncCount == totalIterations) || (isIndexed && gAsyncCount == totalIterations * 200) ) {
77 endTime = process.hrtime(startTime);
78 var totalMS = endTime[0] * 1e3 + endTime[1] / 1e6;
79 var rate = (isIndexed?totalIterations*200:totalIterations) * 1000 / totalMS;
80 rate = rate.toFixed(2);
81 console.log("find (indexed : " + isIndexed + ") : " + totalMS + "ms (" + rate + ") ops/s");
82
83 if (!isIndexed) {
84 isIndexed = true;
85 ndb.ensureIndex({ fieldName: 'customId' }, function (err) {
86 testperfFind();
87 });
88 }
89 }
90 });
91 }
92}
93
94initializeDB();
95