Ajax Bestiary: A Javascript Field Guide
 
Ajax Bestiary: A Javascript Field Guide
 
 

Entries Tagged as 'prototype'

Loopy Optimizations

Posted by Dave Mahon

We all know that code optimization is important, especially when processing large quantities of data. It is also common knowledge that adding layers of code to loops reduces performance. Except this maxim doesn’t always hold when it comes to JavaScript in browsers and even native methods can vary wildly in performance. In fact, in almost all cases, Underscore, jQuery and YUI outperformed any of the native methods. Interestingly, the newest implementation for native looping, forEach, consistently trumped a traditional for (var i = 0; i < 2500; i++) loop.

I set up a testing framework that looped through a normal array instantiated like so:

var data = [];
var v = {}; //This value doesn't seem to affect performance at the data size I chose
 
for (var i = 0; i &lt; loops; i++) { //loops is defined elsewhere
   data.push(v);
}

I looped through this array using the following methods:

  • for loop
  • for … in … loop
  • forEach loop (not supported in IE9 Quirks Mode)
  • Prototype 1.7: Enumerable.each
  • jQuery 1.7.1: $.each
  • Underscore 1.2.3: _.each
  • YUI 3.1.4: YUI.each

Each loop was passed the value of the array element and returned immediately, like so:

//From the native for and for ... in ... tests
(function(el){return;})(data[i]);

I eventually settled upon an array of 2500 elements and running the test 200 times to collect a reasonable number of samples. These numbers were not chosen arbitrarily. Prototype would time out on Firefox at 5000 array elements and Safari seemed to have wildly varying results on each run of the suite with fewer than 200 samples. With 200 samples, the variance in mean time between runs became a few hundredths of a millisecond, not enough to be of consequence. Disturbingly, while Prototype froze the browser with 5000 array elements and 100 samples, it had no issue with 2500 elements and 200 samples. Even so, with some tests averaging less than a hundredth of a millisecond, we will soon require much larger data sets to get meaningful results at all, which may preclude the inclusion of Prototype (and even native methods!) in future tests.

All tests were run in a freshly launched browser on an updated operating system (either MacOS 10.7.2 or Windows 7 Home Premium) running on a MacBook Pro with a 2.53GHz Intel Core 2 Duo processor and 4GB of 1067MHz DDR3 RAM. Firefox had all add-ons disabled and Internet Explorer had the Developer Tools open (to switch between Standards and Quirks mode).

So let’s look at some charts!

Mac safari
This was certainly an interesting start to the process. YUI, Underscore and jQuery all clocked in at 0.005 ms. Prototype would prove to be faster than native methods, with the exception of forEach, on all browsers. Underscore was only be outperformed on IE 9 (32-bit, Standards Mode).

Mac chrome
Chrome was exceptional as well, with the traditional for loop actually running slower than for ... in .... This behavior was also seen on Chrome for Windows and Safari for Windows.

Since all of the major browsers are clearly pre-optimized for these libraries (as they themselves wrap the native looping language structures), let’s look at just the libraries:
Loop run times, by library
Here we can begin to see that Prototype really is behind its peers in loop performance. While we are talking fractions of a millisecond, our apps are growing larger by the day and this could become a serious issue.

Run times of non-prototypical libraries by browser
Hey! It looks like Firefox really is slow. Curiously, IE 9 is significantly faster, which flies in the face of most generalized JavaScript performance metrics.

Still, something looks odd about IE:
Run times by library and version of Internet Explorer 9
Your mileage varies wildly depending on whether you choose standards or quirks mode, and not always in obvious ways. In general, 64-bit is faster, but only marginally, and most people are not using it. (You have to explicitly launch it, as it is not the default, even on 64-bit Windows). Meanwhile, quirks mode apparently embeds some performance hacks. As a note to benchmark developers, this should be evidence enough that not all IE’s are the same and we need to start breaking down by rendering mode and compilation.

So far, we’ve seen the average times and most browsers are quite acceptable. What are the worst case scenarios?

Platform

Browser

Method

Max (ms)

Mean (ms)

Windows 7

IE 9.0.8112.16421 (64-bit IE 9 Quirks)

for

93

5.29

Windows 7

IE 9.0.8112.16421 (32-bit IE 9 Standards)

forEach

81

4.04

Windows 7

IE 9.0.8112.16421 (64-bit IE 9 Quirks)

for in

81

6.27

Windows 7

IE 9.0.8112.16421 (32-bit IE 9 Standards)

for in

76

9.87

Windows 7

IE 9.0.8112.16421 (64-bit IE 9 Standards)

for in

71

4.89

Windows 7

IE 9.0.8112.16421 (32-bit IE 9 Quirks)

for in

67

5.995

MacOS 10.7.2

Firefox 9.0.1

for in

55

1.885

Windows 7

Firefox 9.01

for in

52

6.055

Windows 7

IE 9.0.8112.16421 (32-bit IE 9 Quirks)

for

49

4.66

Windows 7

IE 9.0.8112.16421 (64-bit IE 9 Standards)

for

48

4.76

Windows 7

IE 9.0.8112.16421 (32-bit IE 9 Standards)

for

39

7.845

Windows 7

Chrome 16.0.912.75 m

for in

30

1.13

Windows 7

Chrome 16.0.912.75 m

for

26

1.315

MacOS 10.7.2

Chrome 16.0.912.75

for

23

1.175

MacOS 10.7.2

Chrome 16.0.912.75

for in

22

1.085

MacOS 10.7.2

Safari 5.1.2

for in

16

1

Windows 7

Firefox 9.01

jQuery

6

0.185

MacOS 10.7.2

Safari 5.1.2

for

5

0.52

MacOS 10.7.2

Firefox 9.0.1

for

5

0.7

Those averages hid some extreme variations within Internet Explorer. Fortunately, most of these are found using native language structures, which we know better than to use.

Converting Between Wiki Markup & HTML with Prototype: Part 2 ListsAt

Posted by Don Albrecht

At the end of part 1 of the series, the system could easily handle direct replacement of certain html entities with their wiki markup counterparts.  Unfortunately this was a pretty limited implementation that could only handle those entities that had a direct, symmetrical relationship with html.  In the case of lists, we have to keep track of depth and better cleanup the input text.  We also need to enforce default behavior on the input stream.

Since lists are dependent on dedicated whitespace as part of their markup, we need to clear out all unnecessary white space from the html before processing it.  To do this, we simply replace all whitespace characters with an innocuous single space to remove any extra new lines.

$(textNode).innerHTML = $(textNode).innerHTML.gsub( '\s', '' );

Next we need to cleanup the recursion.  Since we need to know significantly more about the given node to properly assess it.  We can replace the Prototype templates with simple curried function calls and migrate the recursion to the curried methods.

var ConverterTable = {
strong: Converter.curry("'''", null, true),
b:  Converter.curry("'''" , null, true),
em: Converter.curry( "''"  , null, true ),
i:  Converter.curry( "''"  , null, true ),
h1: Converter.curry( '='  , null, false ),
h2: Converter.curry( '=='  , null, false ),
h3: Converter.curry( '==='  , null, false ),
h4: Converter.curry( '===='  , null, false ),
h5: Converter.curry( '====='  , null, false ),
h6: Converter.curry( '======' , null, false ),
ul: Converter.curry('', {li:Converter.curry(['* ', ''], null, false)}, false),
ol: Converter.curry('', {li:Converter.curry(['# ', ''], null, false)}, false),
p:  Converter.curry(['','\n'], null, false)
};

The parameters passed into the individual rules are
The Markup String or an array of strings for start and end tags
An optional library of child rules.  These rules will be applied to any children of the given node before the default rules are applied.
An indication as to the ‘inline-ability’ of the given tag.  This controls the bracketing of the resulting markup with ‘\n’ characters.

The modified Converter now looks to apply rules in the following order
If the node is marked as a stopping point, no recursion proceeds on the branch.
If any over-ridden child rules exist for the given tag, those rules are applied and a memo is passed on to child nodes to denote the depth of the recursion.
Any default rules are processed as per the earlier versions of the code.  Note.  A prototype template is no longer used in favor of simple string construction.
The node itself is removed from the DOM.

function Converter( markupString, nestedRules, inline, textNode, memo ){

var startString, endString;
inline = inline ? ” : ‘\n’;
memo = memo ? memo : ”;
var children =  textNode.childElements();

if( typeof markupString == ‘object’){
startString = inline + markupString[0];
endString = markupString[1] + inline;
} else {
startString = inline + markupString;
endString = markupString + inline;
}

for( i in children){
if( typeof children[i] != ‘function’){
if( nestedRules && typeof nestedRules[children[i].tagName.toLowerCase()] == ‘function’){
startString =  memo.strip() + startString;
nestedRules[ children[i].tagName.toLowerCase() ]( children[i], startString);
} else if( typeof ConverterTable[children[i].tagName.toLowerCase()] == ‘function’){
ConverterTable[children[i].tagName.toLowerCase() ](children[i]);
} else { Converter( ”, nestedRules, true, children[i]), memo }
}
}
textNode.replace(  startString + textNode.innerHTML + endString  );
}

Converting Between Wiki Markup & HTML with Prototype

Posted by Don Albrecht

Wiki’s are amazing and powerful tools, unfortunately their dependence on specialized markup creates a huge barrier to their general adoption in many organizations.  This is a first step at building a wysiwyg editor for wiki markup.  While I will be focussing on the syntax unique to the popular MediaWiki platform, these techniques should be applicable to any wiki system.

The general flow of the converter is as follows:

  1. Converter is passed the root node of an html fragment to translate.
  2. Converter recurses through each of the child nodes and converts them.
  3. Root node tag is replaced with wiki markup.

There’s really only 2 key components involved in this first pass. A converter object and the recursive method.

The Converter Object

The converter object is little more than a collection of name value pairs.  The name corresponds to an html tag.  The value is a Prototype template to use in the direct replacement of the given node. By convention we’ll write all of the tag names for the converter object in lower case.

var Converter = {
strong: new Template("'''#{body}'''"),
b:  new Template("'''#{body}'''"),
em: new Template("''#{body}''"),
i:  new Template("''#{body}''"),
h1: new Template('=#{body}='),
h2: new Template('===#{body}=='),

h3: new Template(‘===#{body}===’),
h4: new Template(‘====#{body}====’),
h5: new Template(‘=====#{body}=====’),
h6: new Template(‘======#{body}======’)  }

The Converter Function

The Converter function always performs 2 checks before attempting to convert a given node.  First it ensures that the node is in fact a node and not a stray function from the Prototype enhanced object.  Next it verifies that a converter exists for the tag.  The toLowerCase() on the tagName is necessary due to the inconsistent behavior browsers demonstrate with this attribute.  While all browsers return the variable in all caps for traditional html, they are not reliable about returning lower case values for xhtml markup.

function convertToWiki( textNode ){
//make sure textNode isn't a function on the object
if( typeof textNode != 'function'){

//provide a way to stop execution on select sub trees
if( !textNode.hasClassName( 'stop')){
$(textNode).childElements().each( convertToWiki );
}

//make sure a converter exists for the given tag
if( liteConverter[ textNode.tagName.toLowerCase() ] ){

//replace the text node with a converted version of itself
textNode.replace( liteConverter[textNode.tagName.toLowerCase()]
.evaluate({body:textNode.innerHTML}));
} } }

WysiHat Prototype Based Rich Text Editor

Posted by Don Albrecht

37 Signals has recently announced a new open source rich text editor built on protoype.

It’s a unique take on the Rich Text Editor that focuses on developers over the kitchen sink.

WysiHat is a WYSIWYG JavaScript framework that provides an extensible foundation to design your own rich text editor. WysiHat stays out of your way and leaves the UI design to you. Although WysiHat lets you get up and running with a few lines of code, the focus is on letting you customize it.

Check it out here:
 http://github.com/37signals/wysihat/tree/master

And Read the announcement here:
Introducing WysiHat: An eventually better open source WYSIWYG editor

Ajax24′s Drop Tabs. A Creative Take on The Tab Box for Scriptaculous

Posted by Don Albrecht

Tab Boxes are one of the most ubiquitous and popular of widgets. They pop up in everything from news sites to accounting software and for good reason. After all, tabs are one of the simplest and most efficient ways to cram more into a given block of screen real-estate than would fit otherwise.

Ajax24′s drop tabs replace the normal tab-box behavior concept with a twist. THese tabs pull blocks of content down from a tab bar to make them available and float them above the background content. (think window blinds or drawers as opposed to tabbed sheets of paper). I have a few reservations about the use of a widget with such slightly unconventional behavior. But all in all, the smooth motions of the widget and it’s novelty surely warrant exploration in more playful interfaces.

You can find the widget at

http://www.flash-free.org/en/2008/04/05/e24tabmenu-–-menu-desplegable-ajax/

Templates in Prototype

Posted by Don Albrecht

 As much as I love jQuery, prototype templates have made it into more than one of my projects because of their versatility and ease of use.  They are a capable and amazing tool for formatting and displaying output on the client side and I thought I’d take a few minutes to dive into them.

So what are templates.  In short they are a string with symbols embedded that are replaced at the time of evaluation to create a new string.  For example:

var apple = { fruit: "apple", variety: "honeycrisp" };

var templ = new Template( "My favorite fruit are #{variety} #{apple}s."  );

console.log(  templ.evalaluate( apple ));

>>> My favorite fruit are honeycrisp apples.

This basic example is really all there is to templates.  But, they can be incredibly useful for formatting and displaying JSON data. and repurposing things in universal ways across an app.

Widget.Blender Smooth Image Morphs For Prototype

Posted by Don Albrecht

Widget.Blender is a handy prototype class to smoothly animate a fade/morph transition between images

Features

  • Start & Stop can be triggered by events
  • Autosizing & Wrapping can be controlled
  • Ability to set a standard base url / dir for all images
  • Ability to start at any arbitrary image
  • Ability to run arbitrary function before blend (Useful for setting caption to display along with image)
  • Supported Browsers:
    • Firefox 2
    • Opera 9
    • IE 6
    • IE 7
    • Safari

Check out Widget.Blender at:

http://www.eternal.co.za/scripts/blender/index.html 

Making The Browser "Aware" of AJAX Requests

Posted by Don Albrecht

I recently discovered a fascinating prototype extension called LOAJAX. While the effect of the extension is a bit hard to describe, it’s immediately obvious when you try the demo’s with and without it. Basically, LOAJAX uses an iFrame crutch to make the browser display all of the interface elements associated with a page load.

How it works:

  1. A normal AJAX XMLHttpRequest is triggered by the AJAX application.
  2. LOAJAX creates a hidden iframe that points to a server script.
  3. The browser displays loading behavior while the iframe loads its source.
  4. The Server Script consists of a massive wait so the load never completes.
  5. When the XMLHttpRequest is completed, LOAJAX stops the iframe load and removes it from the DOM.
  6. The browser stops displaying page load indicators.

You can find more about LOAJAX and check out the demo here:

http://blog.loajax.com/

Proto.IPS A Fast and Easy Prototype Based Type In Place Combo Box

Posted by Don Albrecht

Prototype In Place Select

Meet Proto.IPS a fast and easy prototype based combo box modeled after the gMail Chat Widget.

Features:

  • Automatically saved when user clicks outside the widget (on blur)
  • Ability to select predefined or enter new value

You can find it at Perfection Kills

ProtoCorners: Simple Corner Styling for Prototype

Posted by Don Albrecht

Proto CornerAlright, so sometimes you need to throw a little extra style into a project, a bevel there, rounded corner here.  Proto.Corners allows you to simply generate them programatically. Get it at nurey.com