GeezerVison is showing github.com — util: make mime parsing faster · nodejs/node@aff6017
File tree
Expand file treeCollapse file tree
Open diff view settings
Expand file treeCollapse file tree
Open diff view settings
Collapse file
Copy file name to clipboard +53Lines changed: 53 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const common = require('../common'); |
| 4 | +const assert = require('assert'); |
| 5 | +const { MIMEType } = require('util'); |
| 6 | + |
| 7 | +const bench = common.createBenchmark(main, { |
| 8 | + n: [1e5], |
| 9 | + value: [ |
| 10 | + 'application/json', |
| 11 | + 'text/html; charset=utf-8', |
| 12 | + 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW', |
| 13 | + 'text/plain; charset="utf-8"; foo="b\\"ar"; x=y', |
| 14 | + 'not a mime type', |
| 15 | + ], |
| 16 | + operation: ['parse', 'essence', 'params.get'], |
| 17 | +}); |
| 18 | + |
| 19 | +function main({ n, value, operation }) { |
| 20 | + const length = 1024; |
| 21 | + const array = []; |
| 22 | + let fn; |
| 23 | + switch (operation) { |
| 24 | + case 'parse': |
| 25 | + fn = () => MIMEType.parse(value); |
| 26 | + break; |
| 27 | + case 'essence': |
| 28 | + fn = () => MIMEType.parse(value)?.essence ?? null; |
| 29 | + break; |
| 30 | + case 'params.get': |
| 31 | + fn = () => MIMEType.parse(value)?.params.get('charset') ?? null; |
| 32 | + break; |
| 33 | + default: |
| 34 | + throw new Error(`Unsupported operation ${operation}`); |
| 35 | + } |
| 36 | + |
| 37 | + // Warm up. |
| 38 | + for (let i = 0; i < length; ++i) { |
| 39 | + array.push(fn()); |
| 40 | + } |
| 41 | + |
| 42 | + bench.start(); |
| 43 | + for (let i = 0; i < n; ++i) { |
| 44 | + array[i % length] = fn(); |
| 45 | + } |
| 46 | + bench.end(n); |
| 47 | + |
| 48 | + // Verify the entries to prevent dead code elimination from making |
| 49 | + // the benchmark invalid. |
| 50 | + for (let i = 0; i < length; ++i) { |
| 51 | + assert.notStrictEqual(array[i], undefined); |
| 52 | + } |
| 53 | +} |