Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

property vs var: what are the perfomance issues

Tags:

javascript

Im making a snake game in javascript and im creating the objects and gameloops inside the window.onload function.

window.onload = function() { ... Code ... };

Now Im wondering over the objects Im creating inside the function scope are efficiently used? What is the difference between using these two kinds of declarations?

1:

var Snake = { 
    x: null,
    y: null,
    initialize: function(x, y) { this.x = x; this.y = y },
    position: [x, y], 
    move: function(x, y) { ... Code ... }
}

2:

function Snake(x, y) {
    this.x = x;
    this.y = y;
    this.position = function() { return [this.x, this.y]; };
    this.move = function(x, y) { ... Code ... };
}

Im currently using the 1: case and calling the objects from the scope of window.onload function, for example it looks like this:

Snake.initialize(x, y);
while(some condition) {
    Snake.move(x++, y);
}
and so on...

Is there a difference in memory allocation and is there some performance issues with one over the other?

like image 588
patriques Avatar asked Oct 21 '22 08:10

patriques


1 Answers

The first method only creates one object using object literal notation, while the second method uses the constructor function method which can create several instances of the object.

For example method 2 allows:

var snake1 = new Snake(1,2);
var snake2 = new Snake(2,2);
//now I have two snakes, however method 1 would only ever have one copy of snake.

Using method 1 will provide one global instance of the Snake object for the entire game.

Creating multiple instances of an object is going to require more resources, however in this case it may not be noticeable. If you only need one snake within your game use method one, if you plan on having multiple snakes, method2 is the right approach. I wouldn't worry about performance or resource usage until it becomes an issue within your game.

Article on Constructor Function

like image 97
Kevin Bowersox Avatar answered Oct 24 '22 03:10

Kevin Bowersox