xaviergonz / mobx-keystone

A MobX powered state management solution based on data trees with first class support for Typescript, support for snapshots, patches and much more
https://mobx-keystone.js.org
MIT License
554 stars 25 forks source link

Slow init #503

Open quolpr opened 1 year ago

quolpr commented 1 year ago

Hey! I was testing mobx-keystone performance, and I am curious is there any way to optimize the speed of models creation? I made some tests here

https://codesandbox.io/s/mobx-keystone-slow-init-bcujed?file=/src/index.ts

And 100k model creation looks not so good:

image

I also made a simple mobx example, but of course, it doesn't compare with mobx-keysone itself. But it would be great to have the same performance as mobx has, like 100k creation in 300ms.

P. s.: to see real numbers, you need to open chrome devtools. CodeSandbox console is not reliable

terrysahaidak commented 1 year ago

@quolpr can you try the same benchmarks in production builds? I remember mobx-keystone has lots of dev-only checks. Or, for example, by default it does checks for runtime types only in development, since that information is most useful in dev time.

xaviergonz commented 1 year ago

10k, before some optimizations

justCreatingModel: 156.79ms
bigInitWithoutRefsWithoutAssign: 278.91ms
bigInitWithoutRefsWithAssign: 221.127ms
bigInitWithRefsWithoutAssign: 585.204ms
bigInitWithRefsWithoutAssign: 557.227ms

after some optimizations

justCreatingModel: 152.568ms
bigInitWithoutRefsWithoutAssign: 231.678ms
bigInitWithoutRefsWithAssign: 194.093ms
bigInitWithRefsWithoutAssign: 526.714ms
bigInitWithRefsWithoutAssign: 510.131ms

I'll release the micro optimizations as 1.4.1

Expecting mobx-keystone to be as fast as plain mobx is unrealistic since mobx doesn't have patches, snapshots, a way to know the parent of an object and so on. These things take CPU and RAM. As a rule of thumb, use the best tool for the job (e.g. mobx-keystone for serializable state that needs to be undone or replicated around the network (usually document state), mobx for UI state that doesn't need any of these features).

If there are many items in the document layer, then it might be an option to have them in "raw" from and feeding them to mobx-keystone when needed.

quolpr commented 1 year ago

@xaviergonz got it. Thanks!

xaviergonz commented 1 year ago

PS: 1.4.1 released