Skip to content

Commit edb3d64

Browse files
authored
fetch: improve performance of urlHasHttpsScheme (#3094)
1 parent 83a0fb3 commit edb3d64

File tree

3 files changed

+53
-6
lines changed

3 files changed

+53
-6
lines changed
Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
import { bench, run } from 'mitata'
2+
import { urlHasHttpsScheme } from '../../lib/web/fetch/util.js'
3+
4+
const httpString = 'http://example.com'
5+
const httpObject = { protocol: 'http:' }
6+
const httpsString = 'https://example.com'
7+
const httpsObject = { protocol: 'https:' }
8+
9+
bench('urlHasHttpsScheme "http:" String', () => {
10+
urlHasHttpsScheme(httpString)
11+
})
12+
bench('urlHasHttpsScheme "https:" String', () => {
13+
urlHasHttpsScheme(httpsString)
14+
})
15+
bench('urlHasHttpsScheme "http:" Object', () => {
16+
urlHasHttpsScheme(httpObject)
17+
})
18+
bench('urlHasHttpsScheme "https:" Object', () => {
19+
urlHasHttpsScheme(httpsObject)
20+
})
21+
22+
await run()

lib/web/fetch/util.js

Lines changed: 13 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1168,13 +1168,21 @@ function urlIsLocal (url) {
11681168

11691169
/**
11701170
* @param {string|URL} url
1171+
* @returns {boolean}
11711172
*/
11721173
function urlHasHttpsScheme (url) {
1173-
if (typeof url === 'string') {
1174-
return url.startsWith('https:')
1175-
}
1176-
1177-
return url.protocol === 'https:'
1174+
return (
1175+
(
1176+
typeof url === 'string' &&
1177+
url[5] === ':' &&
1178+
url[0] === 'h' &&
1179+
url[1] === 't' &&
1180+
url[2] === 't' &&
1181+
url[3] === 'p' &&
1182+
url[4] === 's'
1183+
) ||
1184+
url.protocol === 'https:'
1185+
)
11781186
}
11791187

11801188
/**

test/fetch/util.js

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
'use strict'
22

3-
const { test } = require('node:test')
3+
const { describe, test } = require('node:test')
44
const assert = require('node:assert')
55
const { tspl } = require('@matteo.collina/tspl')
66
const util = require('../../lib/web/fetch/util')
@@ -338,3 +338,20 @@ test('parseMetadata', async (t) => {
338338
])
339339
})
340340
})
341+
342+
describe('urlHasHttpsScheme', () => {
343+
const { urlHasHttpsScheme } = util
344+
345+
test('should return false for http url', () => {
346+
assert.strictEqual(urlHasHttpsScheme('http://example.com'), false)
347+
})
348+
test('should return true for https url', () => {
349+
assert.strictEqual(urlHasHttpsScheme('https://example.com'), true)
350+
})
351+
test('should return false for http object', () => {
352+
assert.strictEqual(urlHasHttpsScheme({ protocol: 'http:' }), false)
353+
})
354+
test('should return true for https object', () => {
355+
assert.strictEqual(urlHasHttpsScheme({ protocol: 'https:' }), true)
356+
})
357+
})

0 commit comments

Comments
 (0)