pilcrowonpaper / oslo

A collection of auth-related utilities
https://oslo.js.org
MIT License
1.06k stars 35 forks source link

perf: simpler & faster base32 encode #40

Closed AaronO closed 8 months ago

AaronO commented 8 months ago

This is mainly a PoC, similar room for optimization in other encodings. TLDR: >3x faster on jsc/bun, 1.4x faster on v8/deno

Before

❯ deno run ./src/encoding/base32.bench.ts
Starting base32 encoding benchmark...
1 000 000 iterations of base32 encoding took 574.00ms
Average cost per iteration: 574.00ns

❯ bun run ./src/encoding/base32.bench.ts
Starting base32 encoding benchmark...
1,000,000 iterations of base32 encoding took 870.48ms
Average cost per iteration: 870.48ns

After

❯ deno run ./src/encoding/base32.bench.ts
Starting base32 encoding benchmark...
1 000 000 iterations of base32 encoding took 410.00ms
Average cost per iteration: 410.00ns

❯ bun run ./src/encoding/base32.bench.ts
Starting base32 encoding benchmark...
1,000,000 iterations of base32 encoding took 263.55ms
Average cost per iteration: 263.55ns

Bench code

import { base32 } from "./base32.ts";

const data = crypto.getRandomValues(new Uint8Array(32)); // 32 bytes of random data

console.log("Starting base32 encoding benchmark...");

const start = performance.now();
const N = 1e6;

for (let i = 0; i < N; i++) {
    base32.encode(data);
}

const end = performance.now();
const dt = end - start;
const dtAvg = dt / N;

// Convert duration and cost per iteration to appropriate units
function tUnit(value: number): string {
    if (value < 0.001) {
        return `${(value * 1000000).toFixed(2)}ns`;
    } else if (value < 1) {
        return `${(value * 1000).toFixed(2)}µs`;
    } else {
        return `${value.toFixed(2)}ms`;
    }
}

console.log(`${N.toLocaleString()} iterations of base32 encoding took ${tUnit(dt)}`);
console.log(`Average cost per iteration: ${tUnit(dtAvg)}`);
pilcrowonpaper commented 8 months ago

Ah interesting - forgot that bit shifting "loops" > 32

pilcrowonpaper commented 8 months ago

Can you create a changeset (see CONTRIBUTING.md)?

pilcrowonpaper commented 8 months ago

Thanks!