Generic indexing helpers

Benchmark publishedon

Description

Compare generic helper styles for grouping typed records by a stable key.

Setup

type ClickEvent = { kind: 'click'; x: number; y: number; pressure: number }
type ViewEvent = { kind: 'view'; durationMs: number; depth: number }
type PurchaseEvent = { kind: 'purchase'; cents: number; quantity: number }
type UserEvent = ClickEvent | ViewEvent | PurchaseEvent

const events: UserEvent[] = Array.from({ length: 2_000 }, (_, index): UserEvent => {
  if (index % 5 === 0) return { kind: 'purchase', cents: 299 + index, quantity: (index % 3) + 1 }
  if (index % 2 === 0) return { kind: 'click', x: index % 320, y: index % 180, pressure: (index % 10) / 10 }
  return { kind: 'view', durationMs: 120 + (index % 90), depth: index % 7 }
})

const weights: Record<UserEvent['kind'], number> = {
  click: 3,
  view: 1,
  purchase: 11,
}

Test Runner

Initializing...

Testing in
Test CaseOps/sec
Switch with union narrowing
let score = 0

for (const event of events) {
  switch (event.kind) {
    case 'click':
      score += event.x + event.y + event.pressure * 10
      break
    case 'view':
      score += event.durationMs * event.depth
      break
    case 'purchase':
      score += event.cents * event.quantity
      break
  }
}

return score
ready
Record lookup plus common fields
let score = 0

for (const event of events) {
  score += weights[event.kind]
  if (event.kind === 'purchase') score += event.cents * event.quantity
  else if (event.kind === 'view') score += event.durationMs * event.depth
  else score += event.x + event.y
}

return score
ready
Typed reduce callback
return events.reduce((score: number, event: UserEvent) => {
  if (event.kind === 'purchase') return score + event.cents * event.quantity
  if (event.kind === 'view') return score + event.durationMs * event.depth
  return score + event.x + event.y + event.pressure * 10
}, 0)
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

Revision 1
publishedon