While the following practices may not bring you vast speed improvements (and not doing them will certainly not make your code "bad" in any way), they are nonetheless good habits to get into.
When you're executing a lengthy for
statement, there is no need to make the JavaScript engine work harder than it has to. Take the following example, which calculates the length of the array myArray
every time the loop reruns:
//avoid constant recalculation of the length of myArray for(var c = 0; c < myArray.length; c++){ //do something with myArray[c] }
A much better way of writing this for
statement is to cache the length of the array in a variable. This way, the value of myArray.length
is retrieved only once, and used during the entire loop.
//a better way of looping through myArray var max; for(var c = 0; max = myArray.length,c < max; c++){ //do something with myArray[c] }
If the order that you access the array values in is not important, then it's also slightly quicker to count down than up. This is because it's more efficient to count down to zero than it is to calculate and equate your values to an arbitrary number, such as the length of myArray
. For example:
//looping backwards is faster var c; for(c = myArray.length; c--;){ //do something with myArray[c] } //alternatively, you can use a while loop in this instance while(c--) { //do something with myArray[c] }
Where possible, it's best to use a forEach loop in lieu of a standard for
loop, particularly if you're looping through array values. For example, we could alter our previous sample code to look something like this:
function printResults(element, index, array){ //do something with myArray[index]; Ti.API.info(index + ' = ' + element); } myArray.forEach(printResults);
Sometimes, you simply need to check a single value and determine whether it matches a specific value before proceeding in your code. This might be as simple as determining whether an object is null
, or checking that an operator is true
or false
. In many cases, it's simpler to use a few shortcuts.
//here we are checking if this object is null var myObject; if(myObject !== null) { myObject = { name: 'Boydlee' }; } //a better way of declaring this object would be var myObject = myObject || { name: 'Boydlee' }; //in this example we're checking if a value equals true, and //assigning a variable accordingly var dinner = ''; if(isBritish === true) { dinner = 'Burger & Chips'; } else { dinner = 'Hamburger & Fries'; } //a simpler way to perform this check would be to use the //pattern "variable = (condition) ? True-value : false-value; dinner = isBritish ? 'Burger & Chips' : 'Hamburger & Fries';