Skip to content

Instantly share code, notes, and snippets.

@thegedge
Last active September 26, 2023 17:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save thegedge/edaadd4f334025a0a29b1e702a277c29 to your computer and use it in GitHub Desktop.
Save thegedge/edaadd4f334025a0a29b1e702a277c29 to your computer and use it in GitHub Desktop.
MobX benchmark
import { makeAutoObservable, makeObservable, observable } from "mobx";
import { DataModel, Model, model, prop } from "mobx-keystone";
import { types } from "mobx-state-tree";
function bench(f: () => { value: number }) {
// Warmup
let sum = 0;
for (let index = 0; index < 100_000; ++index) {
sum += f().value;
}
const start = performance.now();
sum = 0;
for (let index = 0; index < 100_000; ++index) {
sum += f().value;
}
return { ms: performance.now() - start, sum };
}
const MSTModel = types.model({
value: types.number,
str: types.string
});
class Clazz {
constructor(readonly value: number, readonly str: string) { }
}
class MobxAutoObservable {
constructor(readonly value: number, readonly str: string) {
makeAutoObservable(this);
}
}
class MobxObservable {
constructor(readonly value: number, readonly str: string) {
makeObservable(this, {
value: observable,
str: observable,
});
}
}
@model("myApp/Model")
class MobxKeystoneModel extends Model({
value: prop<number>(),
str: prop<string>(),
}) {}
@model("myApp/DataModel")
class MobxKeystoneDataModel extends DataModel({
value: prop<number>(),
str: prop<string>(),
}) {}
const results = {
object: bench(() => ({ value: 1, str: "test" })),
class: bench(() => new Clazz(0, "test")),
mst: bench(() => MSTModel.create({ value: 1, str: "test" })),
mobx_ks_model: bench(() => new MobxKeystoneModel({ value: 1, str: "test" })),
mobx_ks_data_model: bench(() => new MobxKeystoneDataModel({ value: 1, str: "test" })),
mobx_class_auto: bench(() => new MobxAutoObservable(1, "test")),
mobx_class_regular: bench(() => new MobxObservable(1, "test")),
mobx_object_auto: bench(() => makeAutoObservable({ value: 1, str: "test" })),
mobx_object_regular: bench(() => makeObservable({ value: 1, str: "test" }, { value: observable, str: observable })),
};
const timings = Object.entries(results);
timings.sort((a, b) => b[1].ms - a[1].ms);
for(const [name, timing] of timings) {
console.log(`${name.padEnd(20)} => ${Math.round(10*timing.ms) / 10}ms`);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment