HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavascriptMinor

Optimize Game of Life

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
lifegameoptimize

Problem

I'm a beginner at coding and the past days I tried to write the famous "Conway's Game of Life" in Angular.js. Right now I'm done with the code and the game works. But if the size of the playground grid gets too big (e.g. 100x100 cells), my program is kind of slow. I wanted to ask you where I could improve my code to make it run more quickly. It would be great for me to see what I have could done in a better way to learn from it.

The following code creates the grid for the playing field and gives the cells their coordinates and alive status:

$scope.createGrid = function(width,height){ // Spielfeld erzeugen
    $scope.playingField = {
        width:width,
        height:height,
        data:[]
    };
    for( var r = 0 ; r < width; r++){
        $scope.playingField.data.push([]);
        for( var c = 0 ; c < height; c++){
            $scope.playingField.data[r].push({ x:c, y:r, alive:false });
        }
    }
    $(".grid").width("600px");
    $(".grid").height("600px");
};


Changes color and live status of a cell when clicked on it:

$scope.clickCell = function(cell){ // Zellen Status ändern. tot / leben
    cell.alive = !cell.alive;
};
$scope.style = function(value) { // Einen Style zuweisen
    return { "background-color": value };
};


This is the part where I think the program gets slowed down. It checks all the cell neighbours and copies a new grid after it; I would be very curious about other solutions to this problem:

```
$scope.startRound = function(){ // Runde durchlaufen
console.time("Benchmark für das kopieren");
// TODO: Kopieren ist zu langsam, muss anders erfolgen!
var newData = angular.copy($scope.playingField.data);
console.timeEnd("Benchmark für das kopieren");
angular.forEach($scope.playingField.data, function(cells,r){
angular.forEach(cells, function(cell,c){
var alive = 0;
//Nachbarn überprüfen
for(var i = r-1 ; i 3)){
newData[r][c].alive = false;

Solution

The problem is that angular.copy is a really slow function (discussion here: https://github.com/angular/angular.js/issues/11099), in order to copy the array without references you could also do something like this:

var newData = JSON.parse(JSON.stringify($scope.playingField.data));


This should be a big improvement in speed.

Code Snippets

var newData = JSON.parse(JSON.stringify($scope.playingField.data));

Context

StackExchange Code Review Q#118387, answer score: 3

Revisions (0)

No revisions yet.