Skip to content

Commit cf37283

Browse files
committed
util: make mime parsing faster
Signed-off-by: James M Snell <jasnell@gmail.com> Assisted-by: Opencode
1 parent 14e8f5b commit cf37283

3 files changed

Lines changed: 373 additions & 216 deletions

File tree

‎benchmark/mime/mimetype-parse.js‎

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
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+
}

0 commit comments

Comments
 (0)