From 5cf8bdb6a8d91fbe0873685f5a2170e6e2fdd52c Mon Sep 17 00:00:00 2001 From: Wojciech Maj Date: Sun, 23 Feb 2025 23:20:57 +0100 Subject: [PATCH 1/3] Refactor parameterCount to optimize performance Now that body-parser targets Node.js 18, we can finally use String.split to count all the '&'s in parameterCount body. This makes the function roughly 2x faster, according to this jsperf: https://jsperf.app/niqepi/2 Fun fact: if you run this jsperf in Firefox, the old implementation will get record-breaking speeds, while the _new_ one will be roughly 7x slower. Thankfully, both Chrome/Node and Bun/Safari engines show the opposite results. --- lib/types/urlencoded.js | 14 ++------------ package.json | 1 - 2 files changed, 2 insertions(+), 13 deletions(-) diff --git a/lib/types/urlencoded.js b/lib/types/urlencoded.js index 687745f8..8a06f23c 100644 --- a/lib/types/urlencoded.js +++ b/lib/types/urlencoded.js @@ -208,19 +208,9 @@ function getCharset (req) { */ function parameterCount (body, limit) { - var count = 0 - var index = 0 + var len = body.split('&').length; - while ((index = body.indexOf('&', index)) !== -1) { - count++ - index++ - - if (count === limit) { - return undefined - } - } - - return count + return len > limit ? undefined : len - 1; } /** diff --git a/package.json b/package.json index 16ff7df7..c2734d21 100644 --- a/package.json +++ b/package.json @@ -44,7 +44,6 @@ "lint": "eslint .", "test": "mocha --reporter spec --check-leaks test/", "test-ci": "nyc --reporter=lcovonly --reporter=text npm test", - "test-cov": "nyc --reporter=html --reporter=text npm test" } } From 85f19f362c2895280f711fc7b76aaadf55f1cc75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ulises=20Gasc=C3=B3n?= Date: Mon, 24 Mar 2025 12:21:17 +0100 Subject: [PATCH 2/3] Update lib/types/urlencoded.js --- lib/types/urlencoded.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/types/urlencoded.js b/lib/types/urlencoded.js index 8a06f23c..ce9531b7 100644 --- a/lib/types/urlencoded.js +++ b/lib/types/urlencoded.js @@ -208,7 +208,7 @@ function getCharset (req) { */ function parameterCount (body, limit) { - var len = body.split('&').length; + var len = body.split('&').length return len > limit ? undefined : len - 1; } From 9a5fcaa7bd62979a3f6931295d56ef0f3ca0db89 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ulises=20Gasc=C3=B3n?= Date: Mon, 24 Mar 2025 12:21:22 +0100 Subject: [PATCH 3/3] Update lib/types/urlencoded.js --- lib/types/urlencoded.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/types/urlencoded.js b/lib/types/urlencoded.js index ce9531b7..f2488344 100644 --- a/lib/types/urlencoded.js +++ b/lib/types/urlencoded.js @@ -210,7 +210,7 @@ function getCharset (req) { function parameterCount (body, limit) { var len = body.split('&').length - return len > limit ? undefined : len - 1; + return len > limit ? undefined : len - 1 } /**