Blog Post default image

Data Access

Accessing Data

Ok so now we have established scope, lets have a look at Data Access for common elements within your JavaScript. Typically these will be the ways in which you access data in JavaScript.

  • Literals (bool)
  • Variables
  • Object Property
  • Array

Accessing data from Variables and Literals is the fastest, with very little difference between them. Accessing data from Object Properties or Arrays is much slower and more expensive.

A typical function using property lookups and arrays

{code type=php}
function process(data) {
if (data.count > 0) {
for (var i=0; i < data.count; i++) { processData(data.item[1]); } } } {/code}

Same function but faster, local variables

{code type=php}
function process(data) {
var count = data.count,
item = data.item;
if (count > 0) {
for (var i=0; iProperty Depth

Simply put, the longer the property lookup, the longer it takes to retrieve!

Long property Look up

{code type=php}
var tmp = object.name.middle.name;
{/code}

Short property Look up

{code type=php}
var tmp = object.name;
{/code}

Pages: 1 2 3 4

2 Comments

  1. Very informative article. I guess it’s simple tips like this that make the difference between light and heavy code. Do these techniques apply to PHP too?

  2. CraigW says:

    I had a function which was taking over 37000ms to execute on IE6 (our company still insist on using IE6) and even 24,000ms in IE8 – Firefox executed the same function in 150ms.

    I discovered the cause – I was using a for – in to iterate around an array and it seems that IE is incapable of optimising for – in loops. I changed the code so it was using a for loop:

    OLD Code

    for (elementNo in myArray)
    {
    }

    NEW Code

    var totalElements = myArray.length;
    for (var elementNo = 0; elementNo < totalElements; elementNo ++)
    {
    }

    This reduced the IE6 time to 700ms (Firefox was 20ms faster).

Post a Comment