Skip to content

Commit

Permalink
fetch: improve performance of urlHasHttpsScheme (#3094)
Browse files Browse the repository at this point in the history
  • Loading branch information
Uzlopak authored Apr 11, 2024
1 parent 83a0fb3 commit edb3d64
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 6 deletions.
22 changes: 22 additions & 0 deletions benchmarks/fetch/url-has-https-scheme.mjs
Original file line number Diff line number Diff line change
@@ -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()
18 changes: 13 additions & 5 deletions lib/web/fetch/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -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:'
)
}

/**
Expand Down
19 changes: 18 additions & 1 deletion test/fetch/util.js
Original file line number Diff line number Diff line change
@@ -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')
Expand Down Expand Up @@ -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)
})
})

0 comments on commit edb3d64

Please sign in to comment.