Skip to content

Commit

Permalink
perf: use insertion sort algorithm (nodejs#2706)
Browse files Browse the repository at this point in the history
  • Loading branch information
tsctx authored and crysmags committed Feb 27, 2024
1 parent 6591901 commit 7961a05
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions lib/fetch/headers.js
Original file line number Diff line number Diff line change
Expand Up @@ -454,11 +454,26 @@ class Headers {

// 2. Let names be the result of convert header names to a sorted-lowercase
// set with all the names of the headers in list.
const names = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1)
const names = [...this[kHeadersList]]
const namesLength = names.length
if (namesLength <= 16) {
// Note: Use insertion sort for small arrays.
for (let i = 1, value, j = 0; i < namesLength; ++i) {
value = names[i]
for (j = i - 1; j >= 0; --j) {
if (names[j][0] <= value[0]) break
names[j + 1] = names[j]
}
names[j + 1] = value
}
} else {
names.sort((a, b) => a[0] < b[0] ? -1 : 1)
}

const cookies = this[kHeadersList].cookies

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

0 comments on commit 7961a05

Please sign in to comment.