From c7a903a7991a39c3e44c55e86955ccf4f95e8a7c Mon Sep 17 00:00:00 2001 From: uzlopak Date: Thu, 2 Feb 2023 21:06:11 +0100 Subject: [PATCH] improve performance of isUtf8MimeType --- benchmarks/isUtf8MimeType.js | 23 +++++++++++++++++++++++ lib/isUtf8MimeType.js | 10 ++++++++-- test/isUtf8MimeType.test.js | 22 ++++++++++++++++++++++ 3 files changed, 53 insertions(+), 2 deletions(-) create mode 100644 benchmarks/isUtf8MimeType.js create mode 100644 test/isUtf8MimeType.test.js diff --git a/benchmarks/isUtf8MimeType.js b/benchmarks/isUtf8MimeType.js new file mode 100644 index 0000000..a68a8bc --- /dev/null +++ b/benchmarks/isUtf8MimeType.js @@ -0,0 +1,23 @@ +'use strict' + +const benchmark = require('benchmark') +const isUtf8MimeType = require('../lib/isUtf8MimeType').isUtf8MimeType + +const applicationJson = 'application/json' +const applicationJavascript = 'application/javascript' +const textJson = 'text/json' +const textHtml = 'text/html' +const textJavascript = 'text/javascript' +const imagePng = 'image/png' + +new benchmark.Suite() + .add('isUtf8MimeType', function () { + isUtf8MimeType(applicationJson) + isUtf8MimeType(applicationJavascript) + isUtf8MimeType(imagePng) + isUtf8MimeType(textJson) + isUtf8MimeType(textHtml) + isUtf8MimeType(textJavascript) + }, { minSamples: 100 }) + .on('cycle', function onCycle (event) { console.log(String(event.target)) }) + .run({ async: false }) diff --git a/lib/isUtf8MimeType.js b/lib/isUtf8MimeType.js index 93a7c5b..d24978a 100644 --- a/lib/isUtf8MimeType.js +++ b/lib/isUtf8MimeType.js @@ -1,6 +1,12 @@ 'use strict' -const utf8MimeTypeRE = /^text\/|^application\/(javascript|json)/ -const isUtf8MimeType = utf8MimeTypeRE.test.bind(utf8MimeTypeRE) +function isUtf8MimeType (value) { + const len = value.length + return ( + (len > 21 && value.indexOf('application/javascript') === 0) || + (len > 14 && value.indexOf('application/json') === 0) || + (len > 5 && value.indexOf('text/') === 0) + ) +} module.exports.isUtf8MimeType = isUtf8MimeType diff --git a/test/isUtf8MimeType.test.js b/test/isUtf8MimeType.test.js new file mode 100644 index 0000000..f718c2a --- /dev/null +++ b/test/isUtf8MimeType.test.js @@ -0,0 +1,22 @@ +'use strict' + +const { test } = require('tap') +const { isUtf8MimeType } = require('../lib/isUtf8MimeType') + +test('isUtf8MimeType', function (t) { + const testCases = [ + ['application/json', true], + ['text/json', true], + ['application/javascript', true], + ['text/javascript', true], + ['application/json+v5', true], + ['text/xml', true], + ['text/html', true], + ['image/png', false] + ] + t.plan(testCases.length) + + for (let i = 0; i < testCases.length; ++i) { + t.strictSame(isUtf8MimeType(testCases[i][0], 'test'), testCases[i][1]) + } +})