Last active
October 14, 2019 15:25
-
-
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?
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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