开发者

How to prevent a javascript stack overflow?

开发者 https://www.devze.com 2023-02-17 18:31 出处:网络
I\'ve been building Conway\'s Life with javascript / jquery in order to run it in a browser Here. Chrome, Firefox and Opera or Safari do this pretty fast so preferably don\'t use IE for this. IE9 is o

I've been building Conway's Life with javascript / jquery in order to run it in a browser Here. Chrome, Firefox and Opera or Safari do this pretty fast so preferably don't use IE for this. IE9 is ok though. While generating the new generations of Life I am storing the previous generations in order to be able to walk back through the history. This works fine until a certain point when memory fills up, which makes the browser(tab) crash.

So my question is: how can I detect when memory is filling up? I am storing an array for each generation in an array which forms the history of generations. This takes massive amounts of memory which crashes the browser after a few thousands of generations, depending on available memory. I am aware of the fact that javascript can't check the 开发者_StackOverflow社区amount of available memory but there must be a way...


I doubt that there is a way to do it. Even if there is, it would probably be browser-specific. I can suggest a different way, though.

Instead of storing all the data for each generation, store snapshots taken every once in a while. Since the Conway's Game of Life is deterministic, you can easily re-generate future frames from a given snapshot. You'll probably want to keep a buffer of a few frames so that you can make rewinding nice and smooth.

In reality, this doesn't actually solve the problem, since you'll run out of space eventually. However, if you store every n frames, your application will last n times longer, which might just be long enough. I would recommend that you impose some hard limits on how far into the past you can rewind so that you have a cap on how much you have to store. Determine that how many frames that would be (10 minutes at 30 FPS = 18000 frames). Then, divide frames by how many frames you can store (profile various web browsers to figure this out) and that is the interval between snapshots you should use.


Dogbert pretty much nailed it. You can't know exactly how much available memory there is but you can know how potentially large your dataset will be.

So, take the size of each object stored in the array, multiply by array dimensions and that's the size of one iteration. Multiply that by the desired number of iterations to see how much space total it will take, and adjust accordingly.

Or, inspired by Travis, simply run the pattern in reverse from the last known array. It is deterministic after all.

0

精彩评论

暂无评论...
验证码 换一张
取 消