Daniel Kalevski
By Daniel Kalevski

Memory optimization for HTML5 games

Memory optimization for HTML5 games

Intro:

Most of the games contains game logic where you need to instantiate a lot of objects from some class like particles that have short lifetime and needs to be destroyed.

Problem:

JavaScript’s model is based on garbage collection pattern. This means that the developer don’t have dirrect control over allocated memory. Memory locations (variables) marked as null will be collected by garbage collector and removed from memory. But when garbage collector needs to dispose a lot of objects, takes a lot of processing time. Neceserry spent processing time is bad for the performance of the game.

In most cases the memory profile will be like this:

fig2

How to fix that

Solution for this kind of problem is implementing Object pools pattern. This implementation will help with reusing disposed objects instead of creating new ones.

After optimization:

fig3

Example

  1. Import object-pool npm module by executing npm install --save object-pool

  2. Replace old implementation

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class GameObject {



    speed = 1



    run() { /* your code */ }

}



let gameObject = new GameObject()

gameObject.run()

with:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51


import pool from 'object-pool'



class GameObject {

    

    speed = 1



    run() { /* your code */ }

}



const gameObjectPool = pool({

    init: () => { // a factory method which should return a freshly created object.

        return new GameObject()

    },

    initSize: 10, // a number to specify the initial size of reserved objects in the pool

    

    disable: gameObject => {

        // reset gameObject properties to default values

        gameObject.speed = 1

    }

})



let gameObject = gameObjectPool.create()

gameObject.run()



For more detailed documentation for the library visit the link.