Skip to content

Commit 2b3c9b7

Browse files
authored
perf: use insertion sort algorithm (#2706)
1 parent f187320 commit 2b3c9b7

File tree

1 file changed

+17
-2
lines changed

1 file changed

+17
-2
lines changed

lib/fetch/headers.js

+17-2
Original file line numberDiff line numberDiff line change
@@ -454,11 +454,26 @@ class Headers {
454454

455455
// 2. Let names be the result of convert header names to a sorted-lowercase
456456
// set with all the names of the headers in list.
457-
const names = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1)
457+
const names = [...this[kHeadersList]]
458+
const namesLength = names.length
459+
if (namesLength <= 16) {
460+
// Note: Use insertion sort for small arrays.
461+
for (let i = 1, value, j = 0; i < namesLength; ++i) {
462+
value = names[i]
463+
for (j = i - 1; j >= 0; --j) {
464+
if (names[j][0] <= value[0]) break
465+
names[j + 1] = names[j]
466+
}
467+
names[j + 1] = value
468+
}
469+
} else {
470+
names.sort((a, b) => a[0] < b[0] ? -1 : 1)
471+
}
472+
458473
const cookies = this[kHeadersList].cookies
459474

460475
// 3. For each name of names:
461-
for (let i = 0; i < names.length; ++i) {
476+
for (let i = 0; i < namesLength; ++i) {
462477
const [name, value] = names[i]
463478
// 1. If name is `set-cookie`, then:
464479
if (name === 'set-cookie') {

0 commit comments

Comments
 (0)