From 601b25d4886f1b6afbcada4ec16640c061927443 Mon Sep 17 00:00:00 2001 From: tsctx <91457664+tsctx@users.noreply.github.com> Date: Tue, 6 Feb 2024 22:24:37 +0900 Subject: [PATCH] perf: use insertion sort algorithm --- lib/fetch/headers.js | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/lib/fetch/headers.js b/lib/fetch/headers.js index 3c022a78d77..504942edc6e 100644 --- a/lib/fetch/headers.js +++ b/lib/fetch/headers.js @@ -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') {