Debian Codegraph @

node/varint/bench.js

raw
1 var N = 1e7
2 var M = 10
3 /*
4 benchmark encoding and decoding N random integers.
5
6 A number is encoded into a buffer, (the buffer is reused so
7 that allocation does not affect the benchmark)
8
9 to test the effect on performance of invalid records
10 (i.e. too short, with the Most Significant Byte missing)
11 every M items, attempt to decode from a shorter slice of the buffer.
12 This will probably be produce an invalid result. We do not
13 need to write into that buffer - because it refurs to the same memory as
14 the full size buffer.
15
16 run with INVALID=1 to include N/M invalid decodes.
17
18 results:
19 with no invalid decodes, I get about 2428 decodes/ms
20 with invalid decodes:
21 old code that overruns buffer: 1122 decodes/ms
22 check length & return undefined: 2439 decodecs/ms
23 check length & return NaN: 2434 d/ms
24 check length & return -1: 2400 d/ms
25
26 conclusion, it doesn't make a significant difference whether
27 what is returned to show an invalid read,
28 but if you overrun the buffer the cost is considerable.
29
30 recomendation: return undefined
31 */
32
33 var buffer = new Buffer(8)
34 var _buffer = buffer.slice(0, 4)
35 var varint = require('./')
36 var l = N
37 var invalid = 0
38
39 includeInvalid = !!process.env.INVALID
40
41 var start = Date.now()
42 while (l--) {
43 var int = Math.floor(Math.random()*0x01fffffffffffff)
44 varint.encode(int, buffer, 0)
45 //console.log(int, varint.decode(buffer, 0))
46 //every 1000 varints, do one that will be too short,
47 //measure
48 if(includeInvalid && !(l%M)) {
49 if(undefined == varint.decode(_buffer, 0))
50 invalid ++
51 } else
52 if(int !== varint.decode(buffer, 0))
53 throw new Error('decode was incorrect')
54 }
55
56 console.log('decode&encode/ms, invalidDecodes')
57 console.log(N/(Date.now() - start) + ',', invalid)