Becki
Becki

Reputation: 41

Chosen.js Performance

I'm trying to use chosen.js for a list with about 1400 entries. It is taking about 1.5 seconds to run the initialisation code for chosen.

Have tracked down that in SelectParser.prototype.add_option() the slow part is html: option.innerHTML

 this.parsed.push({
     array_index: this.parsed.length,
     options_index: this.options_index,
     value: option.value,
     text: option.text,
     html: option.innerHTML,  // <======= here
     selected: option.selected,
     disabled: group_disabled === true ? group_disabled : option.disabled,
     group_array_index: group_position,
     classes: option.className,
     style: option.style.cssText                  
    });

If this is set to simply html: option.text the chosen plugin still seems to work as required.

Are there other implications to changing this & any other tips to improve performance?

Upvotes: 4

Views: 2497

Answers (1)

Wladimir Palant
Wladimir Palant

Reputation: 57681

While HTML serialization is generally a slow operation, I find it surprising that it is supposedly responsible for more than a second delay. A quick test I've run has shown that executing option.innerHTML on 5000 options takes less than 2 milliseconds in Firefox 33 and Chrome 38, other browsers should behave similarly. So I have a suspicion that you identified the source of the issue incorrectly.

Either way, your change has two implications:

  1. Any formatting of the options will be lost, chosen.js will only display pure text. Given that most of the time options are only pure text, that might not be something you care about.
  2. The option text will be inserted as HTML code. This will cause trouble whenever special characters like < are used, this is also a potential source of security issues (XSS). To prevent this your code should contain escaping:
 html: option.text.replace("&", "&amp").replace("<", "&lt;").replace(">", "&gt;"),

Upvotes: 2

Related Questions