Skip to content

Commit 25448c0

Browse files
committed
perf: optimize hash function and cache JSON.stringify result
- Rename hashObject to hashString for clarity - Cache JSON.stringify(value) to avoid duplicate calls - Add comment about JSON.stringify key order behavior
1 parent f8c7ca0 commit 25448c0

File tree

1 file changed

+8
-5
lines changed

1 file changed

+8
-5
lines changed

src/cookies.ts

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -8,13 +8,12 @@ import { InvalidCookieSignature } from './error'
88
import type { Context } from './context'
99
import type { Prettify } from './types'
1010

11-
// FNV-1a hash for fast object comparison
12-
const hashObject = (obj: unknown): number => {
11+
// FNV-1a hash for fast string hashing
12+
const hashString = (str: string): number => {
1313
const FNV_OFFSET_BASIS = 2166136261
1414
const FNV_PRIME = 16777619
1515

1616
let hash = FNV_OFFSET_BASIS
17-
const str = JSON.stringify(obj)
1817
const len = str.length
1918

2019
for (let i = 0; i < len; i++) {
@@ -182,22 +181,26 @@ export class Cookie<T> implements ElysiaCookie {
182181
if (current === value) return
183182

184183
// For objects, use hash-based comparison for performance
184+
// Note: Uses JSON.stringify for comparison, so key order matters
185+
// { a: 1, b: 2 } and { b: 2, a: 1 } are treated as different values
185186
if (
186187
typeof current === 'object' &&
187188
current !== null &&
188189
typeof value === 'object' &&
189190
value !== null
190191
) {
191192
try {
192-
const newHash = hashObject(value)
193+
// Cache stringified value to avoid duplicate stringify calls
194+
const valueStr = JSON.stringify(value)
195+
const newHash = hashString(valueStr)
193196

194197
// If hash differs from cached hash, value definitely changed
195198
if (this.valueHash !== undefined && this.valueHash !== newHash) {
196199
this.valueHash = newHash
197200
}
198201
// First set (valueHash undefined) OR hashes match: do deep comparison
199202
else {
200-
if (JSON.stringify(current) === JSON.stringify(value)) {
203+
if (JSON.stringify(current) === valueStr) {
201204
this.valueHash = newHash
202205
return // Values are identical, skip update
203206
}

0 commit comments

Comments
 (0)