1'use strict'; 2 3const common = require('../common.js'); 4const { MessageChannel } = require('worker_threads'); 5const bench = common.createBenchmark(main, { 6 payload: ['string', 'object'], 7 style: ['eventtarget', 'eventemitter'], 8 n: [1e6] 9}); 10 11function main(conf) { 12 const n = conf.n; 13 let payload; 14 15 switch (conf.payload) { 16 case 'string': 17 payload = 'hello world!'; 18 break; 19 case 'object': 20 payload = { action: 'pewpewpew', powerLevel: 9001 }; 21 break; 22 default: 23 throw new Error('Unsupported payload type'); 24 } 25 26 const { port1, port2 } = new MessageChannel(); 27 28 let messages = 0; 29 function listener() { 30 if (messages++ === n) { 31 bench.end(n); 32 port1.close(); 33 } else { 34 write(); 35 } 36 } 37 38 switch (conf.style) { 39 case 'eventtarget': 40 port2.onmessage = listener; 41 break; 42 case 'eventemitter': 43 port2.on('message', listener); 44 break; 45 default: 46 throw new Error('Unsupported listener type'); 47 } 48 49 bench.start(); 50 write(); 51 52 function write() { 53 port1.postMessage(payload); 54 } 55} 56