Incipit Postgres · capitulum xvi

Benchmarking UUID v4 vs ULID

Benchmarking UUID against ULID.

Fig. i. Benchmarking UUID v4 vs ULID.

tl;dr

ULID offers better performance compared to UUIDs (v4) since ULIDs are monotonic. Another advantage is ULID values can be stored in the UUID column type that postgres offers.

ULID Generation

CREATE EXTENSION IF NOT EXISTS pgcrypto;

CREATE OR REPLACE FUNCTION generate_ulid() RETURNS uuid
    AS $$
        SELECT (lpad(to_hex(floor(extract(epoch FROM clock_timestamp()) * 1000)::bigint), 12, '0') || encode(gen_random_bytes(10), 'hex'))::uuid;
    $$ LANGUAGE SQL;

SELECT generate_ulid();

Benchmarks

UUID (mean = 0.4531, median = 0.48)

ULID (mean = 0.0708, median = 0.037)

Colophon

Here ends the treatise Benchmarking UUID v4 vs ULID, written by Sreeraj Rajan and imprinted in the officina of Sreeraj on the xxii day of Februarii in the year MMXXIII, which is to say 22 February 2023. Laus Deo.

Flashing