From a98e005ab65d00b9af73b07fc78f276da035c25e Mon Sep 17 00:00:00 2001 From: uzlopak Date: Thu, 11 Apr 2024 21:41:09 +0200 Subject: [PATCH] fetch: improve performance of urlHasHttpsScheme --- benchmarks/fetch/url-has-https-scheme.mjs | 22 ++++++++++++++++++++++ lib/web/fetch/util.js | 18 +++++++++++++----- test/fetch/util.js | 19 ++++++++++++++++++- 3 files changed, 53 insertions(+), 6 deletions(-) create mode 100644 benchmarks/fetch/url-has-https-scheme.mjs diff --git a/benchmarks/fetch/url-has-https-scheme.mjs b/benchmarks/fetch/url-has-https-scheme.mjs new file mode 100644 index 00000000000..9e321016d78 --- /dev/null +++ b/benchmarks/fetch/url-has-https-scheme.mjs @@ -0,0 +1,22 @@ +import { bench, run } from 'mitata' +import { urlHasHttpsScheme } from '../../lib/web/fetch/util.js' + +const httpString = 'http://example.com' +const httpObject = { protocol: 'http:' } +const httpsString = 'https://example.com' +const httpsObject = { protocol: 'https:' } + +bench('urlHasHttpsScheme "http:" String', () => { + urlHasHttpsScheme(httpString) +}) +bench('urlHasHttpsScheme "https:" String', () => { + urlHasHttpsScheme(httpsString) +}) +bench('urlHasHttpsScheme "http:" Object', () => { + urlHasHttpsScheme(httpObject) +}) +bench('urlHasHttpsScheme "https:" Object', () => { + urlHasHttpsScheme(httpsObject) +}) + +await run() diff --git a/lib/web/fetch/util.js b/lib/web/fetch/util.js index c6884e3cb98..b7b9602bdbf 100644 --- a/lib/web/fetch/util.js +++ b/lib/web/fetch/util.js @@ -1168,13 +1168,21 @@ function urlIsLocal (url) { /** * @param {string|URL} url + * @returns {boolean} */ function urlHasHttpsScheme (url) { - if (typeof url === 'string') { - return url.startsWith('https:') - } - - return url.protocol === 'https:' + return ( + ( + typeof url === 'string' && + url[5] === ':' && + url[0] === 'h' && + url[1] === 't' && + url[2] === 't' && + url[3] === 'p' && + url[4] === 's' + ) || + url.protocol === 'https:' + ) } /** diff --git a/test/fetch/util.js b/test/fetch/util.js index 7e3c90c1fc3..bb9103facd3 100644 --- a/test/fetch/util.js +++ b/test/fetch/util.js @@ -1,6 +1,6 @@ 'use strict' -const { test } = require('node:test') +const { describe, test } = require('node:test') const assert = require('node:assert') const { tspl } = require('@matteo.collina/tspl') const util = require('../../lib/web/fetch/util') @@ -338,3 +338,20 @@ test('parseMetadata', async (t) => { ]) }) }) + +describe('urlHasHttpsScheme', () => { + const { urlHasHttpsScheme } = util + + test('should return false for http url', () => { + assert.strictEqual(urlHasHttpsScheme('http://example.com'), false) + }) + test('should return true for https url', () => { + assert.strictEqual(urlHasHttpsScheme('https://example.com'), true) + }) + test('should return false for http object', () => { + assert.strictEqual(urlHasHttpsScheme({ protocol: 'http:' }), false) + }) + test('should return true for https object', () => { + assert.strictEqual(urlHasHttpsScheme({ protocol: 'https:' }), true) + }) +})