Skip to content

Instantly share code, notes, and snippets.

@postspectacular
Last active October 14, 2019 15:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save postspectacular/d78b70a859350053fd0ea3efe6f21bc4 to your computer and use it in GitHub Desktop.
Save postspectacular/d78b70a859350053fd0ea3efe6f21bc4 to your computer and use it in GitHub Desktop.
Super slow numeric property accessors - why is [0] / [1] access 110x slower than .x/.y?
import { bench } from "@thi.ng/bench";
import { map, range } from "@thi.ng/transducers";
export class Vec2 {
buf: Float32Array;
constructor(buf: ArrayBuffer, off: number) {
this.buf = new Float32Array(buf, off, 2);
}
get x() {
return this.buf[0];
}
get y() {
return this.buf[1];
}
set x(x: number) {
this.buf[0] = x;
}
set y(y: number) {
this.buf[1] = y;
}
get "0"() {
return this.buf[0];
}
get "1"() {
return this.buf[1];
}
set "0"(x: number) {
this.buf[0] = x;
}
set "1"(y: number) {
this.buf[1] = y;
}
}
const N = 10000;
const buf = new Float32Array(N * 2).fill(1);
const pts = [...map((i) => new Vec2(buf.buffer, i * 8), range(N))];
const updateXY = () => {
for (let i = 0; i < N; i++) {
pts[i].x += 1;
pts[i].y += 2;
}
};
const updateXY2 = () => {
for (let i = 0; i < N; i++) {
pts[i]["x"] += 1;
pts[i]["y"] += 2;
}
};
const update01 = () => {
for (let i = 0; i < N; i++) {
pts[i][0] += 1;
pts[i][1] += 2;
}
};
bench(updateXY, 1000);
// 58ms
bench(updateXY2, 1000);
// 58ms
bench(update01, 1000);
// 6604ms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment