Changes
- Faster Page Loads With Image Concatenation
- Updated the code to use version 1.1.2 of the jQuery library (bundled)
Files
(the greeny thing below this line is a punchcard)
Andrea Ercolino, Software Engineer
(the greeny thing below this line is a punchcard)
There is a jQuery plugin for simplifying access to a select box. It’s very useful and I tried to use it in a prioject where I had to show hundreds of options at once. It worked pretty well with a few options, but as soon as those many options started to come in, performance fell down.
Let’s have a look at the implementation of the addOption function.
{[.addOption_original /enzymes/chili-js.php]}
Off Topic: The code above is a bit complex at first sight. The reason it seems complex is due to unneeded recursion, so common among jQuery developers. In fact the jQuery library itself makes use of unneeded recursion whenever possible…
Look at the snippet below the comment // loop through existing options
. What’s going on here? A select box is treated like a database table where an option is a record and its value is the primary key. When an option is added to a select box, the everlasting dilemma arises: Is it an INSERT or an UPDATE?
The solution implemented here is to loop through existing options and break if a match is found between the new option value and the old ones. Sadly enough, this is the optimal (linear length) solution if you are adding just one option, but it’s the worst (quadratic length) one when you are adding many options at once.
Here is a replacement using a dictionary for storing and retrieving existing options. It’s an inner refactoring with no change on the interface, so it’s pretty simple to copy and use it in your own projects.
{[.addOption_replacement /enzymes/chili-js.php]}
The performance improvement is huge. Here are some figures I got on my PC by means of the Firebug Profiler.
If you want to test it by yourself here is the simple page I used:
{[.testpage /enzymes/chili-web.php]}
In my Chili recipes I use the regexp /(?:.|n)/ when I want to mean each and every char. It cannot be just a dot, because a dot doesn’t match n (AKA new line AKA line feed AKA 0x0A). Due to the fact that I erase from the input any r (AKA carriage return AKA 0x0D) before trying a match, the regexp I use is almost safe, in fact I do not consider u2028 nor u2029, two additional (unicode) new line chars that a dot doesn’t match.
In short, and in general, a safe catch-all regexp is /(?:w|W)/ which means any word char or any non-word char.
So, if you are concerned with these unicode details and can’t wait till the next release of Chili, I advise you to search (?:.|n) and replace any occurrence with (?:w|W).