JS1k: JavaScript Optimisations

Following up on my post on JS1k I thought I’d put together a small list of optimisations you can use if you’re looking to minify your code before compressing it. When you only have 1024 bytes to play with every byte counts!

Very obvious, store your objects for later use. You may need to use the document / context later so store them in a single byte variable.

1
2
3
4
5
6
7
8
//From:
var canvas = document.getElementById('c')
var context = canvas.getContext('2d')

//To:
d=document
t=d.getElementById('c')
c=t.getContext('2d')

If you are using Math object / functions, don’t repeat ‘Math’ over and over. It may not look much at first but it will pay off and save you loads of bytes

1
2
3
4
5
6
7
8
//From:
var colour = Math.floor(Math.random()*255);

//To:
M=Math
R=M.random
L=M.floor
colour = L(R()*255)

I found myself using 2 Pi and false quite a lot in the arc method, so why not minify them too.

1
2
3
4
5
6
7
//From:
context.arc(posX, posY, radius, 0, Math.PI*2, false);

//To (uses Math example above too):
P=M.PI*2
f=false
context.arc(posX, posY, radius, 0, P, f);

For your ‘draw’ function use an anonymous function within setInterval(). This will save you around 5 bytes.

1
2
3
4
5
6
7
8
9
10
//From:
function d(){
    //Code goes here...
}
setInterval(d,9)

//To:
setInterval(function(){
    //Code goes here...
},9)

When it comes to the canvas API it is necessary to minimise it’s usage at times since the methods can’t be stored like we did with the Math object. For that I used a mixture of arrays and for while loops.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//From:
ctx.fillStyle = "red";
ctx.beginPath();
ctx.arc(50, 100, 10, 0, Math.PI*2, false);
ctx.closePath();
ctx.fill();

ctx.fillStyle = "blue";
ctx.beginPath();
ctx.arc(143, 230, 15, 0, Math.PI*2, false);
ctx.closePath();
ctx.fill();//Add more if needed...

//To:
A=["red",50,100,10,"blue",143,230,15];
i=2;while(i--){
    D=i*4;
    ctx.fillStyle = A[D];
    ctx.beginPath();
    ctx.arc(A[D+1], A[D+2], A[D+3], 0, P, f);//We stored 2Pi and false in a var above
    //removed closepath() as this is done when fill is called
    ctx.fill();
}

Another quite obvious one, use the ternary operator instead of an if else statement.

1
2
3
4
5
6
7
8
9
10
//From:
if(Math.ceil(Math.random()*2) == 1){
    var result = 1
} else {
    result = -1
}

//To:
Math.ceil(Math.random()*2) == 1 ? result = 1:result = -1
//Remember you can minify the Math functions

An excellent couple of tips from Ben Almans blog post.

1
2
3
4
5
6
7
8
9
10
11
12
13
/*Backwards iterating while loop*/
//From:
for(i=0;i<20;i++){} //19 bytes

//To:
i=20;while(i--){} //17 bytes

/*Use 'this' instead of 'window'*/
//From:
w=window

//To:
w=this

Hopefully you’ve found some of these JavaScript short-cuts useful. Have any more to add to the list?