• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict';
2
3const common = require('../common.js');
4
5const bench = common.createBenchmark(main, {
6  aligned: ['true', 'false'],
7  method: ['swap16', 'swap32', 'swap64'/* , 'htons', 'htonl', 'htonll' */],
8  len: [64, 256, 768, 1024, 2056, 8192],
9  n: [1e6]
10}, {
11  test: { len: 16 }
12});
13
14// The htons and htonl methods below are used to benchmark the
15// performance difference between doing the byteswap in pure
16// javascript regardless of Buffer size as opposed to dropping
17// down to the native layer for larger Buffer sizes. Commented
18// out by default because they are slow for big buffers. If
19// re-evaluating the crossover point, uncomment those methods
20// and comment out their implementations in lib/buffer.js so
21// C++ version will always be used.
22
23function swap(b, n, m) {
24  const i = b[n];
25  b[n] = b[m];
26  b[m] = i;
27}
28
29Buffer.prototype.htons = function htons() {
30  if (this.length % 2 !== 0)
31    throw new RangeError();
32  for (let i = 0; i < this.length; i += 2) {
33    swap(this, i, i + 1);
34  }
35  return this;
36};
37
38Buffer.prototype.htonl = function htonl() {
39  if (this.length % 4 !== 0)
40    throw new RangeError();
41  for (let i = 0; i < this.length; i += 4) {
42    swap(this, i, i + 3);
43    swap(this, i + 1, i + 2);
44  }
45  return this;
46};
47
48Buffer.prototype.htonll = function htonll() {
49  if (this.length % 8 !== 0)
50    throw new RangeError();
51  for (let i = 0; i < this.length; i += 8) {
52    swap(this, i, i + 7);
53    swap(this, i + 1, i + 6);
54    swap(this, i + 2, i + 5);
55    swap(this, i + 3, i + 4);
56  }
57  return this;
58};
59
60function createBuffer(len, aligned) {
61  len += aligned ? 0 : 1;
62  const buf = Buffer.allocUnsafe(len);
63  for (let i = 1; i <= len; i++)
64    buf[i - 1] = i;
65  return aligned ? buf : buf.slice(1);
66}
67
68function genMethod(method) {
69  const fnString = `
70      return function ${method}(n, buf) {
71        for (let i = 0; i <= n; i++)
72          buf.${method}();
73      }`;
74  return (new Function(fnString))();
75}
76
77function main({ method, len, n, aligned = 'true' }) {
78  const buf = createBuffer(len, aligned === 'true');
79  const bufferSwap = genMethod(method);
80
81  bufferSwap(n, buf);
82  bench.start();
83  bufferSwap(n, buf);
84  bench.end(n);
85}
86