• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Test the speed of .pipe() with sockets
2'use strict';
3
4const common = require('../common.js');
5const net = require('net');
6const PORT = common.PORT;
7
8const bench = common.createBenchmark(main, {
9  len: [4, 8, 16, 32, 64, 128, 512, 1024],
10  type: ['buf'],
11  dur: [5],
12});
13
14let chunk;
15let encoding;
16
17function main({ dur, len, type }) {
18  switch (type) {
19    case 'buf':
20      chunk = Buffer.alloc(len, 'x');
21      break;
22    case 'utf':
23      encoding = 'utf8';
24      chunk = 'ü'.repeat(len / 2);
25      break;
26    case 'asc':
27      encoding = 'ascii';
28      chunk = 'x'.repeat(len);
29      break;
30    default:
31      throw new Error(`invalid type: ${type}`);
32  }
33
34  const writer = new Writer();
35
36  // The actual benchmark.
37  const server = net.createServer((socket) => {
38    socket.pipe(writer);
39  });
40
41  server.listen(PORT, () => {
42    const socket = net.connect(PORT);
43    socket.on('connect', () => {
44      bench.start();
45
46      socket.on('drain', send);
47      send();
48
49      setTimeout(() => {
50        const bytes = writer.received;
51        const gbits = (bytes * 8) / (1024 * 1024 * 1024);
52        bench.end(gbits);
53        process.exit(0);
54      }, dur * 1000);
55
56      function send() {
57        socket.cork();
58        while (socket.write(chunk, encoding)) {}
59        socket.uncork();
60      }
61    });
62  });
63}
64
65function Writer() {
66  this.received = 0;
67  this.writable = true;
68}
69
70Writer.prototype.write = function(chunk, encoding, cb) {
71  this.received += chunk.length;
72
73  if (typeof encoding === 'function')
74    encoding();
75  else if (typeof cb === 'function')
76    cb();
77
78  return true;
79};
80
81// Doesn't matter, never emits anything.
82Writer.prototype.on = function() {};
83Writer.prototype.once = function() {};
84Writer.prototype.emit = function() {};
85Writer.prototype.prependListener = function() {};
86