1'use strict'; 2 3const common = require('../common.js'); 4const assert = require('assert'); 5const bench = common.createBenchmark(main, { 6 source: [ 7 'array', 8 'arraybuffer', 9 'arraybuffer-middle', 10 'buffer', 11 'string', 12 'string-utf8', 13 'string-base64', 14 'object', 15 'uint8array', 16 'uint16array', 17 ], 18 len: [100, 2048], 19 n: [8e5] 20}); 21 22function main({ len, n, source }) { 23 let i = 0; 24 25 switch (source) { 26 case 'array': { 27 const array = new Array(len).fill(42); 28 bench.start(); 29 for (i = 0; i < n; i++) { 30 Buffer.from(array); 31 } 32 bench.end(n); 33 break; 34 } 35 case 'arraybuffer': { 36 const arrayBuf = new ArrayBuffer(len); 37 bench.start(); 38 for (i = 0; i < n; i++) { 39 Buffer.from(arrayBuf); 40 } 41 bench.end(n); 42 break; 43 } 44 case 'arraybuffer-middle': { 45 const arrayBuf = new ArrayBuffer(len); 46 const offset = ~~(len / 4); 47 const length = ~~(len / 2); 48 bench.start(); 49 for (i = 0; i < n; i++) { 50 Buffer.from(arrayBuf, offset, length); 51 } 52 bench.end(n); 53 break; 54 } 55 case 'buffer': { 56 const buffer = Buffer.allocUnsafe(len); 57 bench.start(); 58 for (i = 0; i < n; i++) { 59 Buffer.from(buffer); 60 } 61 bench.end(n); 62 break; 63 } 64 case 'uint8array': { 65 const uint8array = new Uint8Array(len); 66 bench.start(); 67 for (i = 0; i < n; i++) { 68 Buffer.from(uint8array); 69 } 70 bench.end(n); 71 break; 72 } 73 case 'uint16array': { 74 const uint16array = new Uint16Array(len); 75 bench.start(); 76 for (i = 0; i < n; i++) { 77 Buffer.from(uint16array); 78 } 79 bench.end(n); 80 break; 81 } 82 case 'string': { 83 const str = 'a'.repeat(len); 84 bench.start(); 85 for (i = 0; i < n; i++) { 86 Buffer.from(str); 87 } 88 bench.end(n); 89 break; 90 } 91 case 'string-utf8': { 92 const str = 'a'.repeat(len); 93 bench.start(); 94 for (i = 0; i < n; i++) { 95 Buffer.from(str, 'utf8'); 96 } 97 bench.end(n); 98 break; 99 } 100 case 'string-base64': { 101 const str = 'a'.repeat(len); 102 bench.start(); 103 for (i = 0; i < n; i++) { 104 Buffer.from(str, 'base64'); 105 } 106 bench.end(n); 107 break; 108 } 109 case 'object': { 110 const obj = { length: null }; // Results in a new, empty Buffer 111 bench.start(); 112 for (i = 0; i < n; i++) { 113 Buffer.from(obj); 114 } 115 bench.end(n); 116 break; 117 } 118 default: 119 assert.fail('Should not get here'); 120 } 121} 122