Archive

Posts Tagged ‘Javascript’

Javascript “For” Loops and micro-optimizations

June 6th, 2011 No comments

Loops execute a block of code a specified number of times, or while a specified condition is true.

In JavaScript, there are two different kind of loops:

  • for: loops through a block of code a specified number of times
  • for-in: loops that should be used to iterate over non-array objects, an action also called enumeration
  • while: loops through a block of code while a specified condition is true

A typical for loop white you iterate over array-like objects or arrays looks like:

var myArray = [0,1,2,3,4,5,6,7,8,9];

for(var i = 0; i < myArray.length; i++){
    console.log(myArray[i]);
}

This will log the 10 numbers inside the myArray array. This is a way to iterate through myArray’s element but not the optimal.

The problem with the above loop is that the length property of the array is accessed on every iteration and this can slow down things especially while iterating through HTMLCollection objects.

One simple thing you can do is to cache the length property of the collection you are iterating over and to achieve this you can change the above code with the following:

var myArray = [0,1,2,3,4,5,6,7,8,9];

for(var i = 0, length = myArray.length; i < length; i++){
    console.log(myArray[i]);
}

This will have the same result as before but the value of length property will be calculated and retrieved only once during the whole iteration.

One last tweak could be to change the i++ to i+=1 as post-increment and post-decrement have been implicated in many of the worst buffer-overrun security errors. (JSLint also prompts you to do this specifying that ++ and – promote “excessive trickiness”)

var myArray = [0,1,2,3,4,5,6,7,8,9];

for(var i = 0, length = myArray.length; i < length; i+=1){
    console.log(myArray[i]);
}

Other micro-optimizations could be to write the for loop counting down to 0, as it’s faster and more efficient to compare to 0 than to the length of an array or anything else other than 0

var myArray = [0,1,2,3,4,5,6,7,8,9];

for(var i = myArray.length; i-=1){
    console.log(myArray[i]);
}

OR

var i = myArray.length;
while(i-=1){
    console.log(myArray[i]);
}
Categories: Javascript Tags: ,

Minify your Javascript code

June 6th, 2011 No comments

Minification is the process of  eliminating  white  space,  comments,  and  other nonessential parts of the JavaScript code to decrease the size of the JavaScript files that need to be transferred from the server to the browser. This may help you decrease the load time of your web page and there are a lot of tools to help you in this process, called Minifiers.

One thing to remember is that in order to achieve best results, a good practice is to use local variables in your code whenever possible, because Minifiers also rename variables to shorter names… but only when it’s safe to do so. Global variables are not minized as this may break the code. Shorter names will also speed up the lookups when resolving a variable name, and so the code will be faster during runtime.

Yahoo! YUICompressor

It is written in Java and provides a small .jar file that can be used to minify your javascript and css files doing the following steps:

  • Analyze the source JavaScript file to understand how it is structured
  • Then prints out the token stream, omitting as many white space characters as possible and replace all local symbols by a 1 (or 2, or 3) letter symbol wherever such a substitution is appropriate
  • Outputs result in a *.min.js file

The CSS compression algorithm uses a set of finely tuned regular expressions to compress the source CSS file

Usage

java -jar yuicompressor-x.y.z.jar [options] [input file]

Example

java -jar yuicompressor-2.4.6.jar -o hello.min.js hello.min.js
Minify file "hello.js" and output the result in "hello.min.js" file.

Download it here

Google’s Closure Compiler

Google's Closure Cimpiler

The Closure Compiler is a tool for making JavaScript download and run faster. It is a true compiler for JavaScript. Instead of compiling from a source language to machine code, it compiles from JavaScript to better JavaScript. It parses your JavaScript, analyzes it, removes dead code and rewrites and minimizes what’s left. It also checks syntax, variable references, and types, and warns about common JavaScript pitfalls.

Usage Example

java -jar compiler.jar --js hello.js --js_output_file hello-compiled.min.js
Minify "hello.js" to hello-compiled.min.js

Download it here

MinifyJS.com

MinifyJS Online Javascript Minification Tool

MinifyJS.com provides some advanced features to give you even further control over how you compress your Javascript in a minimalistic UI.

  • Simply Copy and paste your Javascript code into the top box
  • Select any advanced options like, compression method, packing/compressing speed, special chartacters
  • Press “Compress Javascript” button.
Categories: Javascript Tags: ,

How to sort a drop down list (select) using jQuery

July 15th, 2010 5 comments

Let’s assume we have a drop down list that it is initialized to display a list of option and programmatically you want to add or remove options. When you add options you might need to sort options in the drop down list based on the text or the value of each option.

Here is a select box with the list of Cities:

dropdown_list_cities

<select id="cities">
    <option value="0">Select City</option>
    <option value="2">Paris</option>
    <option value="3">London</option>
    <option value="4">Athens</option>
    <option value="5">Mexico</option>
</select>

In order to add a new city, let’s say Rome, and resort them you can do that client side using jQuery:

// Add a last option to the cities drop down list
$("#cities").append($('<option/>').attr('value', '1').text('Rome'));

// Sort by name
$("#cities").html($("#cities option").sort(function (a, b) {
    return a.text == b.text ? 0 : a.text < b.text ? -1 : 1;
}));

// Sort by Value
// If you don't convert a.value to integers javascript will assume
// that a.value and b.value are strings
$("#cities").html($("#cities option").sort(function (a, b) {
    var aValue = parseInt(a.value);
    var bValue = parseInt(b.value);
    return aValue == bValue ? 0 : aValue < bValue ? -1 : 1;
}));

// Reselect the first option
$('#cities').val('0');

What took me some time to figure out is that the value options should be converted to integers before sorting them as javascript will consider them as strings

Categories: Javascript, Web Design Tags: ,

JSON.NET Library

January 13th, 2010 No comments

Json.NET is a lightweight library that allows you to convert classes from .NET to JSON and back again. One of the key features is that allows you to use LINQ for reading and writing JSON. JSON in contrast to XML offers a very lightweight way to feed javascript objects in order to make ajax calls as light as possible

Some Key Features:

  • Flexible JSON serializer to convert .NET objects to JSON and back again
  • LINQ to JSON for reading and writing JSON
  • Writes indented, easy to read JSON
  • Convert JSON to and from XML
  • Supports Silverlight and the Compact Framework

Here is an example of how easy it is to use it:

Article article = new Article
{
ID = 1,
Title = "Article Test 1",
InsDate = DateTime.Now,
Authors = new string[] { "author1", "author2" }
};

Article deserializedArticle = JsonConvert.DeserializeObject<Article>(output);

And the output is:

{
ID": "1",
"InsDate": "\/Date(1292868060000)\/",
"Title": "Article Test 1",
"Authors": [
"author1",
"author2"
]
}
Categories: Libraries Tags: ,