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: ,

Video: Aaron Koblin – Artfully visualizing our humanity

May 28th, 2011 No comments

Today I watched a really great video about Aaron Koblin and some projects he participated trying to visualize huge amounts of data.

The talk is really impressing and some projects are extremely cool, especially the last one about Johnny Cash. In that project he creates a video, called “Ain’t No Grave”, tribute to Johnny Cash from crowd-sourced drawing and the result is amazing.

Here you can view the talk:

A small documentary about Johnny Cash video and the actual result:

If you are an artistic type of person, have a look at project’s web site, I am sure you ‘ll like it!

Categories: Videos Tags: ,

Fast update loads of records in your database

October 28th, 2010 No comments

When you have a database and you want to update a record you simply use an update statement like:

UPDATE table_name
SET col1 = col1 + 1, col2 = col1
WHERE col3 = 'something'

But what about when you want to update thousands of data and the where clause in your statement change continuously?

Let’s assume you have a table called ‘user_activity’:

id user_id ranking
1 23 66237
2 24 452763
3 25 23546345
4 26 87645

The ranking for our users could be calculated programmatically and then in order to update the results we would use the following statements

UPDATE user_activity
SET ranking = 12354
WHERE user_id = 23;

UPDATE user_activity
SET ranking = 5874252
WHERE user_id = 24;

UPDATE user_activity
SET ranking = 47821
WHERE user_id = 25;

UPDATE user_activity
SET ranking = 58214775
WHERE user_id = 26;

Now imaging that the table_activity has more columns, more where clauses (like date for example) and more records.

Something different and faster could be the following approach:

  1. Create a temporary table
  2. BULK insert your calculated results and also any other necessary columns
  3. Update target table using the temporary one
  4. Delete temporary table

Here is the code for our approach:

-- Create temporary table
CREATE TEMPORARY table 'user_activity_temp' (
    user_id int NOT NULL,
    ranking int NOT NULL
);

-- BULK Insert values to the temporary table
INSERT INTO user_activity_temp VALUES
(23, 123454), (24, 5874252), (25, 47821), (26, 58214775);

-- Update target table with the temorary's table results
UPDATE user_activity ua, user_activity_temp uat
SET ua.ranking = uat.ranking
WHERE ua.user_id = uat.user_id;

-- Delete your temporary table
DROP user_activity_temp;
Categories: Tips & Tricks Tags: ,

Clouds

August 26th, 2010 No comments

This is a photo taken in a beautiful place near my village Amfikleia, Greece. I think it’s so beautiful it’s worth submitting it to a challenge called Clouds in dpreview

If you like it, please vote !!!

There are really amazing shots in this challenge but mine is the best :)

Categories: Photography Tags: