# JavaScript Performance: for vs. while

## JavaScript Loops

If you have read some preformance tests on JavaScript loops, you may have heard that “while” is faster than “for”. However the question is how faster is “while”? Here are some results, but first let’s take a look on the JavaScript code.

#### The for experiment

```console.time('for'); for (var i = 0; i < 10000000; i++) { i / 2; } console.timeEnd('for');```

#### The while experiment

```console.time('while'); var i = 0; while (i++ < 10000000) { i / 2; } console.timeEnd('while');```

Note – these tests are performed and measured with Firebug on Firefox.

## Results

It’s a fact, that you’ll get different results as many times as you run this snippet. It depends also on the enviroment and software/hardware specs. That is why I performed them 10 times and then I took the average value. Here are the values of my performance tests. Note that both for and while perform 10,000,000 iterations.

## And the Winner Is

While is the winner with an average result of 83.5 milliseconds, while “for” result is 88 average milliseconds.

As the diagram bellow shows, the while loop is slightly faster. However we should be aware that these performance gains are significant for large number of iterations!

# Friday Algorithms: JavaScript Merge Sort

## Merge Sort

This week I’m going to cover one very popular sorting algorithm – the merge sort. It’s very intuitive and simple as it’s described in Wikipedia:

• If the list is of length 0 or 1, then it is already sorted. Otherwise:
• Divide the unsorted list into two sublists of about half the size.
• Sort each sublist recursively by re-applying merge sort.
• Merge the two sublists back into one sorted list.

## Here’s the Source

(JavaScript)

```var a = [34, 203, 3, 746, 200, 984, 198, 764, 9];   function mergeSort(arr) { if (arr.length < 2) return arr;   var middle = parseInt(arr.length / 2); var left = arr.slice(0, middle); var right = arr.slice(middle, arr.length);   return merge(mergeSort(left), mergeSort(right)); }   function merge(left, right) { var result = [];   while (left.length && right.length) { if (left[0] <= right[0]) { result.push(left.shift()); } else { result.push(right.shift()); } }   while (left.length) result.push(left.shift());   while (right.length) result.push(right.shift());   return result; }   console.log(mergeSort(a));```

It’s interesting to see what happens in the Firebug’s console:

```[34, 203, 3, 746] [200, 984, 198, 764, 9]   [34, 203] [3, 746]   [34] [203]   [3] [746]   [200, 984] [198, 764, 9]   [200] [984]   [198] [764, 9]   [764] [9]   [3, 9, 34, 198, 200, 203, 746, 764, 984]```

Actually the tricky part in this algorithm is the merge function – it does all the work.

# Modyfing Response Headers with Zend Framework

You’ve probably seen that you can track the server response headers with Firebug – a wonderful extension to Firefox.

But have you ever asked yourself how to change a response header with Zend Framework.

Typically this is done with the built in PHP function header, where you can setup the header the page must return, but how to make it with Zend Framework?

It’s pretty simple of course, it’s Zend Framework in fact. To be more precise I’ll post a snippet:

```\$response = \$this->getResponse(); \$response->setHeader('content-type', 'application/x-javascript; charset=utf-8'); \$response->sendResponse();```

# CSS Priority: The Difference Between a.my-class and .my-class

## Do You Know What’s an Inefficient CSS Selector?

Perhaps! I was curious how can inefficient selectors impact a page performance. To begin with this topic let me say that inefficient selector is referred usually as nested selector:

```div span div { border:1px solid red; }```

as you can see here there are three nested tags I use to reference the innermost div. If you’re wondering how you’d know about inefficient selectors – well there is a plugin for the Firebug written by a Google team called Page Speed explaining which of your selectors are inefficient. See the image below.

In the demo page you can find what I was trying to achieve and you can play around with that code to measure by yourself the performance of the different selectors.

## So who’s faster? Nested, IDs or Classes?

Actually its pretty though to say. Yet another surprise for me was to notice that the notation:

`div.my-class {}`

was a bit slower than the marked as “inefficient” by Page Speed:

`div span div {}`

Another good thing to mention is that there is a difference between div.my-class and .my-class

In fact div.my-class is always with a higher priority than .my-class even if you’ve the following code:

```div.my-class { border:1px solid red; }   .my-class { border:1px solid blue; }   div span div { border:1px solid black; }```

And the computed style for Firefox was …

where “div span div” chain matches the same elements as the previous selectors, as you can see:

so even that div.my-class will be the most important and finally the element will get its red border! It does not depend only on where you put the CSS rules, but also on how they are defined.

# How to detect a variable existence in JavaScript?

## Preface

After reading one of the latest posts from Stoyan Stefanov’s blog – phpied.com I stumbled upon an interesting construction in JavaScript describing how to check an object property existence. I’m going to cover this case using as an example the console object, which comes with the Firebug enabled, and I think it may be very useful, just because this object is widely used, but doesn’t exists over all the browsers, even under Firefox when Firebug is disabled. This construction is known as the IN statement and it looks something like that:

`property in object`

which I’m going to cover later in details.

## How you detect a variable existence?

There are three main ways to detect the existence of a property I see in my practice.

1. The most widely used:

`if ( console ) { ... }`

2. The second and more professional one:

`if ( typeof console != 'undefined' ) { ... }`

3. And finally the third and most unknown:

`if ( console in window ) { ... }`

Of course two of them are wrong! Which one should be changed?

## Is everything working correctly? No!

Lets see how they are working. First of all I’m going to test all of them on Firefox 3.6 either with enabled and disabled Firebug, just shouting with old school’s alert().

Now the first one using the IN statement:

```if ( console in window ) alert('object exists!'); else alert('object doesn\'t exists!');```

With Firebug disabled the answer is … nothing! No alert! That’s because the syntax is wrong. There’s an error within the IF statement. We should modify a bit the first row like that:

```if ( 'console' in window ) alert('object exists!'); else alert('object doesn\'t exists!');```

Now everything’s OK. With a disabled Firebug the answer is: “object doesn’t exists!”, and after enabling it, normally the “object exists!”.

Lets move on the next example:

```if ( console ) alert('object exists!'); else alert('object doesn\'t exists!');```

With Firebug enabled the answer is as we expect: “object exists!”, but after disabling it yet again – nothing?! Why’s that? Because the console object doesn’t exists anymore and the IF statement doesn’t return true or false, but simply crashes. How to modify the code? Simply by adding a window.console instead of console.

```if ( window.console ) alert('object exists!'); else alert('object doesn\'t exists!');```

Than the answer is: “the object doesn’t exists!” after what we expected!

The third method is the mostly used, just because it’s completely clear what’s the goal of the IF statement:

```if ( typeof console != 'undefined' ) alert('object exists!'); else alert('object doesn\'t exists!');```

In both disabled and enabled Firebug the answer is as expected!

Now the IN statement may be used if not for the console, but for checking the existence of a property of within an object.