Game Development Reference
In-Depth Information
When you're writing code, always think beforehand about the various solutions that solve a
particular problem, and choose the one that fits best. This doesn't necessarily have to be the most
efficient solution all the time. If one solution is slightly less efficient but results in much clearer code,
it might be a good idea to go for that solution. There are tools that measure the bottlenecks in code.
For Firefox, the Firebug tool has a profiler that can analyze your code to give you an idea of where
the most time is spent. Similarly, Chrome's developer tools include a Benchmark Suite that can
profile JavaScript performance.
Being able to choose the best solution for a problem requires knowledge about what is happening
when code is interpreted and executed. Sometimes inefficiencies may be easy to solve, but you
don't know they exist. Consider the following basic for instruction, which increments each element
in an array by one:
for (var i = 0; i < myArray.length; i++)
myArray[i] += 1;
This for instruction is straightforward, but it isn't very efficient. In each iteration of the loop, the
length of the array is retrieved and compared to the counter. Because retrieving the length of the
array costs time, the following for instruction is more efficient:
for (var i = 0, l = myArray.length; i < l; i++)
myArray[i] += 1;
In this case, you retrieve the length of the array and store it in a variable. The condition of the loop is
executed each iteration, but because it now uses the variable instead of directly retrieving the length,
the code is more efficient.
You can improve the code even more. Incrementing the counter is done by the following instruction:
i++
Let's look in a bit more detail at this instruction. It's possible to use it as follows:
var i = 10;
var j = i++;
Although the second instruction looks a bit strange, it's perfectly valid JavaScript code. This is
because i++ is also an expression , and so it has a result that you can store in a variable. The result
of the i++ expression is the value of i before it was incremented. As a result, j will contain the value
10 and i will contain the value 11 after the second instruction has been executed. Because of this,
i++ needs to create a temporary variable to store that value and return it. However, in the earlier for
loop, you don't use that temporary value. There is another way to increment the variable, as follows:
++i
This does exactly the same thing as i++ , except that it returns the new value of i :
var i = 10;
var j = ++i; // j and i both contain the value 11
Search WWH ::




Custom Search