Skip to content

compare dates as numbers - #303

Open
hood wants to merge 1 commit into
d3:mainfrom
hood:perf/date-compare
Open

hood wants to merge 1 commit into
d3:mainfrom
hood:perf/date-compare

Conversation

@hood

@hood hood commented Nov 21, 2026

Copy link
Copy Markdown

I was profiling a dashboard that loads ~100k rows from a CSV and sorts and bins them by a date column (node --cpu-prof), and d3.sort(data, d => d.date) alone took about half a second.

Comparing two Dates with < or >= goes through ToPrimitive on both sides every time, which is way slower than comparing numbers, and sort, bin and extent do several comparisons per value. Sorting 100k Dates with a plain a < b comparator is 6-8x slower than sorting the same values as numbers, in V8, SpiderMonkey and JSC alike.

This converts Dates once with valueOf() before comparing, through a tiny primitive helper, in ascending, descending, ascendingDefined (so sort, quickselect, rank etc. get it too), extent, min, max, minIndex, maxIndex and bin. Returned values are still the original Date objects, and since < on a Date already compares valueOf() the order is the same, null and Invalid Date included.

Tests pass, and I fuzzed ~8.6k random inputs (Dates, null, Invalid Date, NaN, strings, mixed types) against main with identical results.

Numbers

M1 Pro, node 26, main 24c015e, median of 5 runs of the harness below:

100k rows main this PR
sort(data, d => d.date) 499 ms 58 ms
extent(data, d => d.date) 16.4 ms 0.93 ms
bin().value(d => d.date).thresholds(months) 128 ms 7.8 ms
sort(data, d => d.value) 43.6 ms 39.2 ms

Number sorts don't get slower (last row), the extra instanceof is basically free.

harness

Save as bench.js in the repo root and run node bench.js on main and on this branch.

import {bin, extent, sort} from "./src/index.js";

let seed = 42;
const random = () => (seed = seed * 16807 % 2147483647) / 2147483647;
const start = Date.UTC(2021, 0, 1);
const data = Array.from({length: 1e5}, () => ({date: new Date(start + random() * 3 * 365 * 864e5), value: random()}));
const months = Array.from({length: 37}, (_, i) => new Date(Date.UTC(2021, i, 1)));

function bench(name, f) {
  for (let i = 0; i < 3; ++i) f();
  const times = [];
  for (let i = 0; i < 9; ++i) {
    const t0 = performance.now();
    f();
    times.push(performance.now() - t0);
  }
  times.sort((a, b) => a - b);
  console.log(`${name}\t${times[4].toFixed(2)} ms`);
}

bench("sort(data, d => d.date)", () => sort(data, d => d.date));
bench("extent(data, d => d.date)", () => extent(data, d => d.date));
bench("bin by month", () => bin().value(d => d.date).thresholds(months)(data));
bench("sort(data, d => d.value)", () => sort(data, d => d.value));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

1 participant