Game of life code is slow

I wrote a quick script to implement the iteration procedure in Conway's game of life. It works much slower than expected; even computing a 10*10 grid causes a noticeable pause. In fact, if you run the project, it doesn't need a "wait" block because the time to calculate the new grid is so great.

I have tried wrapping the computation in a warp block, which helps somewhat but doesn't resolve the issue.

The project is Snap! Build Your Own Blocks (, and the particular code block I'm trying to fix is "iterate life". Any help would be appreciated.

First off - 1st time I've seen that method of checking/counting all the neighbours by setting centre cell to value of 8 :slight_smile:

1st (little) improvement is to not bother range checking the x values as if the index is out-of-bounds you just get null returned which isn't an issue

Got it down to 12secs (from 14 for original on my computer) - I changed the forever loop to iterate only 32 times to stop once it reaches steady state

2nd add blank rows to start and end of array and then no need for y bound checking either

Gets it down to 9 secs on my computer

3rd - remove need for i and j loops - now we off to the races - 2 secs on mine :slight_smile:
(and we don't need to add the extra rows)

You should also only check and calculate the cells that need to be calculated, so you're not wasting time on cells that won't change.

How to you do that without looping over them at least once?

You keep a list full of active cells and check only around those cells that are listed in the active cell list.

Well, that's a completely different way of approaching the game :slight_smile:

That's how I did it with mine, it runs quick even with a 50x50 grid (2500 cells).

Thanks for the suggestions! These sped up my code quite a bit.
One question: how did you implement 'sum'? I'm assuming it's a custom block because I couldn't find it in the preset blocks or in any library. I ended up using the APL primitives library for this.

I should still note that this seems "not very fast". Am I missing something, or is snap just not that performant?

It's what the plus block turns into if you place a list on top of it

Quite a few blocks transmogrify like this :slight_smile:

That's cool. Thanks!

This is a good optimization. With that approach, you could even get rid of the array, which would give you the possibility of an "infinite" grid.

I remember I made a Scratch project like that.

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.