Friday, June 22, 2012

Magento search doesn’t work correctly

Sometimes you have done your Magento template with customizing the search result to show nice layout with resulted products. But whoops, your search result is not correct even though you do re-index in the backend, clean cache and look everything around the code core. But you are not getting correct result and you can’t find anything more to make it work. Please try following simple way.
Goto this file \app\design\frontend\default\<your_template>\layout\catalogsearch.xml, then make sure you have added below code. (because sometime we have lacked it)
<catalogsearch_result_index translate="label">
        <reference name="left">
            <block type="catalogsearch/layer" name="catalogsearch.leftnav" after="currency" template="catalog/layer/view.phtml"/>
        <!-- something here ... -->

magento 1.3 Fatal error: Method Varien_Object::__tostring() cannot take arguments in \lib\Varien\Object.php on line 488

When installing the Magento, you have got this error
Fatal error: Method Varien_Object::__tostring() cannot take arguments in D:\PamySoft\Study\Magento\Magento132\lib\Varien\Object.php on line 488
Solution to fix: 2 steps
Step 1)  At the file: <magento>/lib/Varien/Object.php (Line 484)
Change from:

public function __toString(array $arrAttributes = array(), $valueSeparator=',')

public function __invoke(array $arrAttributes = array(), $valueSeparator=',')
Step 2) At the File <magento>/app/code/core/Mage/Core/Controller/Request/Http.php (Line 274)
Change from:

$host = split(':', $_SERVER['HTTP_HOST']);

$host = explode(':', $_SERVER['HTTP_HOST']);
Checked at:  Magento

Thursday, June 14, 2012

open source projects built with yii

List of open source projects built with yii, this is the partial list, if you know others let me know.

 Hamster  Forum software
 Celestic Open source project manager
Zurmo CRM
Customer Relationship Management – CRM
X2 Engine
Customer Relationship Management – CRM
Bug tracker application
Question and answer site like stackoverflow
Flexica CMS
Content Management System
Phundament CMS
Content Management System
Content Management System
Content Management System
Web 2.0 CMS
Content Management System
Content Management System
Content Management System
blog web application
Simple Project Manager / Bug Tracker
Wiki application/module
Open Real Estate Used to built websites of real estate agencies and realtors.

Tuesday, June 12, 2012

Developing A Design Workflow In Adobe Fireworks

Every designer has their own workflow when starting a new project, even if it’s only loosely defined in their head. A typical Web project goes through a variety of steps from inception to launch, with a lot of moving parts throughout the cycle. Photoshop, Illustrator, Fireworks and even Web browsers themselves are available to aid us in our work. But with so many choices, how do we determine the right tool to move from concept to functional design?
Developing A Design Workflow In Adobe Fireworks
Over the years, I have come to rely on Adobe Fireworks as the main workhorse among my design applications. It’s built from the ground up to create screen-ready graphics; it’s object-oriented by design; and it’s lightning fast for creating UI elements. While Photoshop has made great strides lately by adding some vector support, it simply has not been able to match the speed and reusability of Fireworks for production work. Read on to get a glimpse of my project workflow (sketches → wireframes → graphic comps → export) and to see how Fireworks fits into these different stages.


Sketching is arguably the most valuable part of my design process. In terms of workflow, this step isn’t specific to Fireworks, but it’s still a crucial part of getting my ideas flowing.
Dribbble shot by Joshua Bullock
Sketched icons
Dribbble shot by Joshua Bullock
“Quest” (another sketch on paper)
Sketched designs can be done simply with paper and pen or created directly in Fireworks, and they can end up being works of art in and of themselves. I start most projects with sketching in some shape or form, and I use a few different techniques depending on the time and materials available.

High-Fidelity Sketching

Hi-fi sketching is a great option. It allows the designer to forgo the digital tools and break out the pencil, pens and paper.In previous posts outlines this in far greater detail than we can here, so check it out. Because high-fidelity sketches exist on paper, they have permanence; and collaborating on sketches is easy by passing them around, drawing on them and making notes about necessary changes. But by all means, make copies of your work; I wouldn’t want to get angry emails saying that I told you to let others draw all over your beautiful illustrations! High-fi sketches can provide good guidance for development
Hi-fi sketches of mobile screens and interactions
“But why should we start with sketching?” you might ask. The reason is because getting caught up in pixel-precision this early on in a project by going straight to digital is just too easy, and it’ll cost a bit of time in the long run. Remember, Fireworks is all about speed and production, and dropping back to pencil and paper is both a fast and easy way to get your ideas out so that you can start iterating. For those of you who truly enjoy the old-school ways of pencil and paper, here’s a selection of templates built specifically for that purpose. I’ve used these for both mobile and desktop website designs, and they can really help keep your UI consistent and speed your sketching along.
Do not be afraid to explore lots of concepts
Don’t be afraid to explore many concepts and iterations.

Sharpie and a Big Pad of Paper

Using a simple Sharpie or other marker and a big pad of paper is quick, inexpensive and fairly low-fi (meaning there doesn’t need to be as much detail). This lets you capture big ideas and quickly define broad concepts in the design. You can pick up a Sharpie and a huge pad of paper at a local office-supply shop. Throwing away or recycling these drawings is not a problem either — they’re not exactly pages in a sketchbook.
Quick aside: When David Gray interviewed Jason Fried of 37signals, they spoke about exactly this type of low-fi sketching. Gray drew the notes of their conversation, and this fascinating sketched conversation can be seen on Gray’s website. The “big pads of paper” mentioned by Fried in the video can be found on Edward Tufte’s website.
Jason Fried on Design
Jason Fried on design
Pro tip: Sketches can help define site maps and user flows in the absence of a project brief. Are you making a brochure website, a CMS, or a single-page design with tiered layers driven by JavaScript scrolling? Sketching your designs can help cultivate your ideas and reduce design time.

Whiteboard and a Camera

This is the option I usually default to, because a whiteboard offers the same speed as a Sharpie and paper but making changes is easier, and you’re not wedded to particular ideas. A whiteboard is impermanent, and it makes for a great projection surface, with collaborators being able to suggest changes in a meeting room. Large whiteboards can be expensive, but you should be able to find smaller whiteboards at your local office-supply retailer for prices that won’t break the bank. I keep a poster-sized whiteboard (24 × 36 inches) at home for just such occasions.
Different logo concepts - do not be afraid of revisions
Your concepts don’t have to carry heavy detail — just capture the big ideas.

Sketch in Adobe Fireworks

One of the most beautiful features of Fireworks is that it allows you to create vector objects but also offers full-featured bitmap editing. Fireworks supports Wacom tablets and pressure sensitivity to a degree, but it’s not nearly as fluid as what’s available in Photoshop. That being said, Fireworks does allow you to “paint” vector strokes, and I’ve done this with varying degrees of success. The advantage here is that, while it may not be quite as free-form as traditional media, you don’t have to jump through additional hoops, and your sketches will already be on a digital canvas.
Pro tip: When using a Wacom tablet for sketching, use a large canvas size, such as 2500 × 2500 pixels. Because tablets are sensitive, drawing on a small canvas accurately can be difficult. With a large canvas, you get better control and can zoom in to add fine detail.
In my typical workflow, I toss my initial ideas onto a whiteboard, snap a photo of the board with my iPhone, and email it to myself (or save it to Dropbox). At that point, it’s easy to pull the sketch into Fireworks to start building a wireframe in layers on top of the photo.
Snapping a quick picture with a mobile phone or point-and-shoot of a whiteboard sketch
Snap a quick picture of your sketch with your mobile phone, and email it to yourself.
Photos of sketched materials can work well too
Photos of sketches work well if you don’t have a scanner.


Thinking in Patterns

When building a wireframe in Fireworks, one of the most important things is to think in patterns. This doesn’t mean using the design patterns or common interface conventions that users often look for in a design, such a text box for site-wide search. Rather, it means thinking about whether certain elements should share similar formatting throughout the design? Items in a sidebar, content lists, user profiles and photos are all good candidates. Fireworks can already help by creating these content blocks as reusable UI elements in your document library. You can select a group of objects and convert them into a single symbol (we’ll talk about creating symbols soon), and then simply drag it from the document library onto the design as needed. If changes are needed, simply update the library symbol, which will update all other instances throughout the document.
Pro tip: is a popular CSS framework for creating fixed-width designs. A Fireworks extension for is available that automatically creates guides spaced out for the framework. If you’ve already made the jump to responsive design, check out Matt Stow’s Export Responsive Prototype, which exports your Fireworks slices to simulate a responsive layout when you create reflowed designs as separate pages. And if you have no idea what the difference is between fixed-width and responsive design, we’ve got that covered, too.

Creating Pages

I’ll typically start with the header, along with other UI elements that repeat through the website, such as the search box and sidebars. I can then take these elements and define them in my “master” page in the Pages panel. By doing this, any new pages I create will share these elements. They remain locked and on their own layer, so I can design more freely and save time by not having to reconstruct them for each new section that I add to the website. To create a master page, right-click on an existing page in the Pages panel and choose “Set as Master Page” in the pop-up menu.
Creating your first Master page (Master page drop down menu)
Creating a master page
This is really where pattern-based thinking helps. Will your sidebar have its own background colors and texture? If so, you might want to define this on the master page. However, if some pages will expand to the full width of the design, then defining a sidebar here might not be the best solution. Pages have their own unique properties, including canvas width and height, resolution and exporting options, which we’ll discuss later. Hopefully, these ideas will help you identify good candidates for master pages. Webdesign Tuts+ offers a great video tutorial by Connor Turnbull titled “Getting Started With Fireworks: Using Master Pages, Pages and Web Layers.” Remember that pages can have unique dimensions, which is a huge advantage in Fireworks. Adding your header to the master page is fine, because it is anchored at the top of the browser window, but the page’s length can vary. The footer is probably not something to include on the master page, but it can be used very powerfully as a library symbol, so let’s look at symbols next.
Pages in Fireworks help define repeatable sections throughout your site, defined on the master page
All new pages now include repeatable elements defined on the master page — headers, footers and sidebars that are easy to update.

Creating and Using Symbols

Returning to the concept of reusability, the document library in Fireworks can be an indispensable tool for items you intend to reuse. Library symbols can contain groups of objects, enabling you to quickly replicate blocks for a CMS. Need a log-in form in the form of a modal dialog to appear on multiple pages? Create that as a library symbol, complete with the background overlay in the size of your canvas, and drag it from the library to your canvas to illustrate the effect. If you need to make changes to the log-in modal dialog at that point, those changes will be reflected in every instance of the symbol, on every page, on every layer!
To create a symbol, select the objects that you’d like to include (for example, in the footer), and choose “Convert to Symbol” (Modify → Symbols → Convert to Symbol, or press F8 on your keyboard). The text, shapes and anything else you had selected are now available from the Document Library panel, and you can drag the symbol onto the pages as needed. Later, if you decide to make changes to the footer symbol, just make the changes once and they will propagate to every page on which the symbol appears!
The Document Library is where all of your symbols are stored
You’ll find any symbols that you have created in the Document Library panel.
Noupe has a great collection of reusable Fireworks library objects that can be used for prototyping and design. Also worth mentioning is the fantastic Fireworks Wireframing Kit website by Hannah Milan, another great place for UI components.

Graphic Comps

Once the client has approved the wireframes, we can jump into enhancing the website’s underlying skeleton with high-fidelity design. Fireworks allows us to make this transition without ever leaving the application — we enjoy the same functionality of multiple pages and library objects, but now we can add gorgeous photography, beautiful typography and striking color enhancements, all in this one program.

Vectors and Bitmaps

Now that we’ve created the wireframes, we’re ready to get the color and typography flowing. As mentioned, Fireworks combines both bitmap editing and vector object creation in a single powerful package. I usually create as much as possible in vector format because the files are scalable and can be reused for Web and print. The vector editing tools in Fireworks are easy to use, and many of the features you’ll find in Illustrator for manipulating vector objects are available here, too. Editing tools for bitmap and vector can be found in the Tools toolbar, and there is a separate panel for combining and editing vectors (the Path panel).
Fireworks offers bitmap and vector editing tools all without having to leave a single application
Fireworks offers both bitmap and vector editing tools.
Vector drawing created in Fireworks (original art by Erin Potter)
A vector drawing created in Fireworks

Layers, Sub-layers, Groups

In Fireworks, layers work more like they do in Illustrator than in Photoshop, so keep this in mind. Both layers and individual objects can be named, which helps dramatically with exporting if you need to send the graphic files to another designer or developer. I usually name my main layers according to the overall sections of the comp, and then place objects into sublayers to keep them organized. Layer names such as “header” and “twitter block” clearly communicate to other designers which elements of the UI are where in the layout. In addition to layers, Fireworks also supports the grouping of objects and arranging of individual objects and symbols from front to back. This provides an additional level of control when you’re overlapping objects and effects.

Property Inspector Panel

Arguably the single-most powerful UI component in Fireworks is the Property Inspector (PI) panel. The PI panel can be normally found at the bottom of the screen when you first open a new document in Fireworks. Fills, strokes, gradients, patterns, object position, scale and opacity, blending modes, live filters, text properties and much more can all be defined quickly and easily from the PI panel. It’s a convenient place to quickly inspect and change the properties of all kinds of objects! And let’s not forget about Live Filters, which are the secret sauce for making Fireworks a fast tool for production.
Many people ask where the true power of Fireworks lies relative to Photoshop. The answer is the features and behavior of the PI panel. It is your one-stop shop for a vast amount of tweaking. If you’ve ever used Dreamweaver, you’ll be familiar with the panel floating at the bottom of the screen and the myriad of controls it offers.
Object, text and canvas controls are all conveniently laid out in the Property Inspector panel
The PI panel provides controls for text, bitmap and vector objects, live filters, compound shapes, the document canvas and more.

Applying (Live) Filters

Just as we apply adjustment layers and effects in Photoshop, we can apply live filters to objects in Fireworks, and these are all assigned in the PI panel. When you use filters in library symbols, such as glows and drop shadows, they are considered a part of the object and can cause the x and y positions of that element to fluctuate. Live filters can also be applied to symbol instances so that their positions better line up with your grid. It really depends on whether you need the filter to appear in every instance of the symbol or not.
Live filters can also be combined and stacked on top of one another, and they’re multiplicative, which means you can apply more than one instance of the same filter to an object. For example, you can create a very thin, heavy glow around an object, and then apply a secondary glow of another color that’s lighter and more diffused, making for an entirely new treatment. Live filters can be edited at any time simply by double-clicking the filter that you’ve applied and changing its settings. Additionally, live filters can be rearranged by dragging them into a new order, giving you substantial control over applied effects.
Fireworks live filters are placed on any object through the Properties panel (PI panel)
The live filters magic happens in the PI panel.
Keep in mind that using live filters is different than applying filters via Fireworks’ top menu. Live filters remain editable, whereas “regular” filters do not, so I’d recommend using live filters by default. That being said, live filters can affect how much memory Fireworks uses. If your design becomes too complex, you can branch a single UI component or section of the page into its own file to maintain editability, then flatten the layers and bring that object back into your primary comp as a bitmap.
Fireworks vectors and effects scale well for creating icons
Iconography created in Fireworks


Now that we’ve converted the wireframe into a high-fidelity full-color design, it’s time for the transition to a fully functional website using HTML and CSS. We’ll use Fireworks’ superior compression and exporting abilities to pick apart different parts of the design to be used as background images for headings, buttons and even tiled backgrounds.

Defining Slices

When the design comp is completed, it’s time to export the image files for use in the browser. Slices work similar to those in Photoshop; they allow you to define a section of the graphic comp as a flat bitmap image to use on the website or in the CSS. But Fireworks has the additional benefit of allowing us to define specific optimizations and file formats in different slices of the same document. GIF, JPG and PNG images can all exist in the same Fireworks document, and you don’t have to leave the app or go through multiple passes of file exporting, as you might in Photoshop or Illustrator.
Slices exist on their own Web layer above the rest of the design, so they’re easily toggled on and off with the number 2 on your keyboard (or using the eye icon next to the Web layer).
Slices can quickly be toggled on and off
Slices can quickly be toggled on and off in their own layer.
You could manually draw slices with the Slice tool from the default toolbar, but because Fireworks is object-oriented, you can simply select your object or group and choose “Create slice” (Edit → Insert → Rectangular Slice). The slice will be created automatically and set to the size of your object, including any live filters that you’ve applied.
Pro tip: Use the Slice tool to quickly determine the size of an object or icon to ensure that live filters such as glows and drop-shadow filters are not inadvertently cropped out of the final image.
Fireworks slices also enable us to define different parts of the overall comp using unique optimization, naming and file formats, and it gives us one-click exporting options, saving all of these parts in a single location on our computer. No need to get creative with cropping or creating separate files — it’s all done within Fireworks. Simply select your objects and choose Edit → Insert → Rectangular Slice (Alt/Option + Shift + U), then go to the Optimize panel and either select from the presets provided by Fireworks or define your own settings for each slice.
Slices are the secret power of Adobe Fireworks
Slices are the secret power of Fireworks, enabling you to quickly define elements in the design for exporting.
Keep in mind that backgrounds are part of the slice, but these items can easily be placed on their own background layer with the visibility toggled off, giving your buttons and other UI elements full alpha transparency, thus maximizing their versatility.
Pro tip: You can quickly export slice objects after having made minor adjustments. Simply right-click the slice and choose “Export selected slice” to send the image out with your pre-defined settings. This also works when selecting multiple slices, each with their own optimization options. Keep in mind when using this technique that if you’ve changed the image “scale” in the exporting options (say, to create a thumbnail or a website preview for a WordPress theme), then you’ll need to go back into the export preview and reset the size to 100%, or else your sliced exports might look squished.

Exporting Defaults

Slices can either inherit the default exporting option for the file format (set in the Optimize panel) or be unique; meaning you can set a single slice to export as a JPG, while the rest of the image exports as PNG or GIF. This affords tremendous control for different parts of your graphic comp. Many times I’ve also created a separate page in my file titled “Exports” for background sprites and toolbars, which keeps my original image intact — very helpful in the event that the client wants to see the proposed changes. Simply select the relevant UI elements from the design, create a new page, and paste your objects into this new canvas. Once you have the UI elements for the sprite, you will easily have the exact pixel locations to plug into the CSS.
Pro tip: Fireworks saves natively in PNG format (with added meta data), which is easily viewable in a browser. I’ve used this feature in a pinch to quickly show graphic comps to clients and coworkers. But beware: multi-page layouts can get pretty big, which affects downloading time. Also note that the first page in a Fireworks document is what’s shown as the default view of the Fireworks PNG.

Exporting Options

Once you’ve created your slices, or if you’re simply exporting the entire comp to show a client, you’ll be taken to the exporting window in Fireworks. This works similar to the “Save for Web and Devices…” preview in Photoshop and Illustrator. Here you can once again change the level of compression, as well as see a live preview of the image in different file formats.
Export Preview gives us a quick look at sizes and quality of exported image
Export Preview gives us a quick look at the size and quality of the exported image.
You can also control the scale of the graphic — very helpful when you’re designing an icon for multiple devices and platforms (the standard and Retina-sized images for the iPhone display come to mind). You can also export HTML along with the images; export with or without slices; and save the file for use in other applications such as Photoshop or Illustrator.
Pro tip: Use the “Constrain proportion” options and scaling in the “File” tab to quickly export snippets of the design for posting to websites such as Dribbble or for promotional images for a feature area.

Try It Out

There you have it: a super-short synopsis of how to take your sketched ideas to wireframes and all the way to full-color graphic comps using Adobe Fireworks. The power of vector and bitmap editing, the easy and fast control over reusable objects, the excellent live filters and the very good compression and exporting options all make Fireworks a powerful tool for any (screen) designer.
Many of you already own a copy of Fireworks, having bought Adobe Creative Suite, but have simply never opened it up. It doesn’t cost anything to fire up this dormant app and see whether it provides some enhancements to your workflow. Why not give it a try? A streamlined workflow awaits!

JavaScript Profiling With The Chrome Developer Tools

Your website works. Now let’s make it work faster. Website performance is about two things: how fast the page loads, and how fast the code on it runs. Plenty of services will make your website load faster, from minimizers to CDNs, but making it run faster is up to you.
Little changes in your code can have gigantic performance impacts. A few lines here or there could mean the difference between a blazingly fast website and the dreaded “Unresponsive Script” dialog. This article shows you a few ways to find those lines of code with Chrome Developer Tools.

Establish A Baseline

We’ll look at a simple application called a color sorter, which presents a grid of rainbow colors that you can drag and drop to mix up. Each dot is a div tag with a little CSS to make it look like a circle.
The Color Sorter
Generating my rainbow colors was a little tricky, so I got a little help from “Making Annoying Rainbows in JavaScript.”
The page loads pretty fast, but it still takes a moment and blinks a little before it paints. Time to profile the page and make it faster.
Always start performance-improvement projects with a baseline understanding of how fast or slow your application already is. The baseline will let you know whether you’re making improvements and help you make tradeoffs. For this article, we’ll use Chrome Developer Tools.
The profiler is part of Chrome Developer Tools, which is always available in Chrome. Click the “Tools” menu under the little wrench to open it. Firebug has some profiling tools, too, but the WebKit browsers (Chrome and Safari) are best at profiling code and showing timelines. Chrome also offers an excellent tool for event tracing, called Speed Tracer.
To establish our baseline, we’ll start recording in the “Timeline” tab, load our page and then stop the recording. (To start recording once Chrome Developer Tools is open, click the “Timeline” tab, and then the small black circle icon for “Record” at the very bottom of the window.) Chrome is smart about not starting to record until the page starts to load. I run it three times and take the average, in case my computer runs slowly during the first test.
Performance baseline 1
My average baseline — i.e. the time between the first request for the page and the final painting of the page in the browser — is 1.25 seconds. That’s not bad, but it’s not great for such a small page.
I want to make my code run faster, but I’m not sure what’s making it slow. The profiler helps me find out.

Create A Profile

The timeline tells us how long our code took to run, but that doesn’t help us know what’s going on while it’s running. We could make changes and run the timeline again and again, but that’s just shooting in the dark. The “Profiles” tab gives us a better way to see what’s going on.
Profilers show us which functions take the most time. Let’s make our baseline profile by switching to the “Profiles” tab in Chrome Developer Tools, where three types of profiling are offered:
  1. JavaScript CPU profile
    Shows how much CPU time our JavaScript is taking.
  2. CSS selector profile
    Shows how much CPU time is spent processing CSS selectors.
  3. Heap snapshot
    Shows how memory is being used by our JavaScript objects.
We want to make our JavaScript run faster, so we’ll use the CPU profiling. We start the profile, refresh the page and then stop the profiler.
The first profile
The first thing that’s clear from the profile is that a lot is going on. The color sorter uses jQuery and jQuery UI, which are doing a lot of stuff like managing plugins and parsing regular expressions. I can also see that two of my functions are at the top of the list: decimalToHex and makeColorSorter. These two functions take a total of 13.2% of my CPU time, so they’re a good place to start making improvements.
We can click the arrow next to the function calls to open the complete function-call stack. Expanding them, I see that decimalToHex is called from makeColorSorter, and makeColorSorter is called from $(document).ready.
Here’s the code:
1$(document).ready(function() {
2    makeColorSorter(.05, .05, .05, 0, 2, 4, 128, 127, 121);
3    makeSortable();
Knowing where they’re called from also makes clear that making the colors sortable isn’t my biggest performance problem. Performance issues resulting from the addition of a lot of sortables is common, but my code is taking more time to add DOM elements than to make them sortable.
I want to start making those functions faster, but first I want to isolate my changes. A lot happens when the page loads, and I want to get all of that out of my profile.

Isolate The Problem

Instead of loading the color sorter when the document is ready, I’ll make a second version that waits until I press a button to load the color sorter. This isolates it from the document loading and helps me profile just the code. I can change it back once I’m done tuning performance.
Let’s call the new function testColorSorter and bind it to a clickable button:
1function testColorSorter() {
2    makeColorSorter(.05, .05, .05, 0, 2, 4, 128, 127, 121);
3    makeSortable();
1<button id="clickMe" onclick="testColorSorter();">Click me</button>
Changing the application before we profile could alter the performance of the application unexpectedly. This change looks pretty safe, but I still want to run the profiler again to see whether I’ve accidentally changed anything else. I’ll create this new profile by starting the profiler, pressing the button in the app and then stopping the profile.
The second profile
The first thing to notice is that the decimalToHex function is now taking up 4.23% of the time to load; it’s what the code spends the most time on. Let’s create a new baseline to see how much the code improves in this scenario.
The second baseline
A few events occur before I press the button, but I only care about how long it took between the times the mouse was clicked and the browser painted the color sorter. The mouse button was clicked at 390 milliseconds, and the paint event happened at 726 milliseconds; 726 minus 390 equals my baseline of 336 milliseconds. Just as with the first baseline, I ran it three times and took the average time.
At this point, I know where to look and how long the code takes to run. Now we’re ready to start fixing the problem.

Make It Faster

The profiler only tells us which function is causing the problem, so we need to look into it and understand what it does.
1function decimalToHex(d) {
2    var hex = Number(d).toString(16);
3    hex = "00".substr(0, 2 - hex.length) + hex;
5    console.log('converting ' + d + ' to ' + hex);
6    return hex;
Each dot in the color sorter takes a background color value in hex format, such as #86F01B or #2456FE. These values represent the red, green and blue values of the color. For example, Blue dot has a background color of #2456FE, which means a red value of 36, a green value of 86 and a blue value of 254. Each value must be between 0 and 255.
The decimalToHex function converts these RGB colors to hex colors that we can use on the page.
The function is pretty simple, but I’ve left a console.log message in there, which is just some debugging code we can remove.
The decimalToHex function also adds padding to the beginning of the number. This is important because some base-10 numbers result in a single hex digit; 12 in base 10 is C in hex, but CSS requires two digits. We can make the conversion faster by making it a little less generic. I know that the numbers to be padded each have one digit, so we can rewrite the function like this:
1function decimalToHex(d) {
2    var hex = Number(d).toString(16);
3    return hex.length === 1 ? '0' + hex : hex; }
Version three of the color sorter changes the string only when it needs the padding and doesn’t have to call substr. With this new function, our runtime is 137 milliseconds. By profiling the code again, I can see that the decimalToHex function now takes only 0.04% of the total time — putting it way down the list.
The third profile
We can also see that the function using the most CPU is e.extend.merge from jQuery. I’m not sure what that function does because the code is minimized. I could add the development version of jQuery, but I can see that the function is getting called from makeColorSorter, so let’s make that one faster next.

Minimize Content Changes

The rainbow colors in the color sorter are generated from a sine wave. The code looks at a center point in the color spectrum and creates a wave through that center point over a specified width. This changes the colors into a rainbow pattern. We can also change the colors in the rainbow by changing the frequency of the red, green and blue.
01function makeColorSorter(frequency1, frequency2, frequency3,
02                         phase1, phase2, phase3,
03                         center, width, len) {
05    for (var i = 0; i < len; ++i)
06    {
07       var red = Math.floor(Math.sin(frequency1 * i + phase1) * width + center);
08       var green = Math.floor(Math.sin(frequency2 * i + phase2) * width + center);
09       var blue = Math.floor(Math.sin(frequency3 * i + phase3) * width + center);
11       console.log('red: ' + decimalToHex(red));
12       console.log('green: ' + decimalToHex(green));
13       console.log('blue: ' + decimalToHex(blue));
15       var div = $('<div class="colorBlock"></div>');
16       div.css('background-color', '#' + decimalToHex(red) + decimalToHex(green) + decimalToHex(blue));
17       $('#colors').append(div);
19    }
We could take out more console.log functions. The calls are especially bad because each is also calling the decimalToHex function, which means that decimalToHex is effectively being called twice as often as it should.
This function changes the DOM a lot. Every time the loop runs, it adds a new div to the colors div tag. This makes me wonder whether that’s what the e.extend.merge function was doing. The profiler makes it easy to tell with a simple experiment.
Instead of adding a new div each time the loop runs, I want to add all of the div tags at once. Let’s create a variable to hold them, and then add them once at the end.
01function makeColorSorter(frequency1, frequency2, frequency3,
02                         phase1, phase2, phase3,
03                         center, width, len) {
05    var colors = "";
06    for (var i = 0; i < len; ++i)
07    {
08       var red = Math.floor(Math.sin(frequency1 * i + phase1) * width + center);
09       var green = Math.floor(Math.sin(frequency2 * i + phase2) * width + center);
10       var blue = Math.floor(Math.sin(frequency3 * i + phase3) * width + center);
12       colors += '<div class="colorBlock" style="background-color: #' +
13           decimalToHex(red) + decimalToHex(green) + decimalToHex(blue) + '"></div>';
14    }
16    $('#colors').append(colors);
This small change in the code means that the DOM changes once, when it adds all of the div tags. Testing that with the timeline, we see that the runtime between the click and the paint events is now 31 milliseconds. This one DOM change has brought the time for version four down by about 87%. We can also run the profiler again and see that the e.extend.merge function now takes up such a small percentage of the time that it doesn’t show up on the list.
We could make the code one notch faster by removing the decimalToHex function entirely. CSS supports RGB colors, so we don’t need to convert them to hex. Now we can write our makeColorSorter function like this:
01function makeColorSorter(frequency1, frequency2, frequency3,
02                         phase1, phase2, phase3,
03                         center, width, len) {
05    var colors = "";
06    for (var i = 0; i < len; ++i)
07    {
08       var red = Math.floor(Math.sin(frequency1 * i + phase1) * width + center);
09       var green = Math.floor(Math.sin(frequency2 * i + phase2) * width + center);
10       var blue = Math.floor(Math.sin(frequency3 * i + phase3) * width + center);
12       colors += '<div class="colorBlock" style="background-color: rgb(' +
13           red + ',' + green + ',' + blue + ')"></div>';
14    }
16    $('#colors').append(colors);
Version five runs in only 26 milliseconds and uses 18 lines of code for what used to take 28 lines.

JavaScript Profiling In Your Application

Real-world applications are much more complex than this color sorter, but profiling them follows the same basic steps:
  1. Establish a baseline so that you know where you’re starting from.
  2. Isolate the problem from any other code running in the application.
  3. Make it faster in a controlled environment, with frequent timelines and profiles.
There are a few other rules to follow when tuning performance:
  1. Start with the slowest parts first so that you get the most improvement for the time spent tuning.
  2. Control the environment. If you switch computers or make any other major changes, always run a new baseline.
  3. Repeat the analysis to prevent anomalies on your computer from skewing the results.
Everyone wants their website to run faster. You have to develop new features, but new features usually make a website run slower. So, investing time in tuning the performance does pay off.
Profiling and tuning cut the final color sorter’s runtime by over 92%. How much faster could your website be?