Skip to content

Instantly share code, notes, and snippets.

@shinout
Created July 11, 2014 12:48
Show Gist options
  • Save shinout/a654632cf123ad37d99b to your computer and use it in GitHub Desktop.
Save shinout/a654632cf123ad37d99b to your computer and use it in GitHub Desktop.
benchmark: parsing 3byte-uint in CoffeeScript
rt = require "random-tools" # https://github.com/shinout/random-tools
N = 1000000
d = []
i = 0
# data preparation
while i < N
n = rt.randomInt(256 * 256 * 256 - 1)
b = new Buffer(3)
b.writeUInt16BE(n >> 8, 0)
b.writeUInt8(n & 0xff, 2)
d.push [n, b, b.toString("hex")]
i++
# parseInt 16
console.time "h"
for v in d
h = v[2]
n = parseInt h, 16
#console.assert n is v[0]
console.timeEnd "h"
# reads buffer
console.time "b"
for v in d
b = v[1]
n = b.readUInt16BE(0) * 256 + b.readUInt8(2)
#console.assert n is v[0]
console.timeEnd "b"
@shinout
Copy link
Author

shinout commented Jul 11, 2014

h: 94ms
b: 45ms

Reading integers from buffer is faster than parsing hexed string into decimal.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment