Doing some profiling on an application, I discovered something interesting about how Hash works in prototype. See if you can tell the difference between these two operations:
// Method 1
$H
all: "are"
your: "belong to"
base: "us"
toJSON;
// Method 2
HashtoJSON
all: "are"
your: "belong to"
base: "us"
;
The difference is subtle, but important. The first option turns your anonymous object into a Hash object by extending it’s prototype, then calls the instance method Hash#toJSON(). The second version calls a class method Hash::toJSON() and passes in the anonymous object. The resulting string is identical. The performance impact, however, is not. It turns out that the class method version is startlingly faster.
The reasoning for this has to do with how prototype handles enumeration of hashes. Internally, Hash#_each uses a “for in” loop to iterate over every property of the object. Because $H() adds a whole bunch of methods to the prototype of the object, the enumerator also has to check each property to make sure it’s not part of the prototype before passing it to the iterator method. What this boils down to is a whole bunch of extra effort for method one above as it first has to append a bunch of methods to the object, then iterate over them just moments before they’re forgotten without ever actually being used.
The moral of the story is, while the documentation may show an example using method 1, you should probably be using method 2.