prototypejs / prototype

Prototype JavaScript framework
http://prototypejs.org/
Other
3.54k stars 640 forks source link

Inefficient String.unfilterJSON() #202

Open jwestbrook opened 10 years ago

jwestbrook commented 10 years ago

previous lighthouse ticket #968 by Michael M Slusarz


For the most common use case of unfilterJSON() - filtering out the comment delimiters as defined in Prototype.JSONFilter, the current version of unfilterJSON() is inefficient. There is no need to use a matching regex when the search strings are static, and their position is known (at beginning and end of string). This variation is much better:

/* More efficient String.unfilterJSON() function. */
Object.extend(String.prototype, {
    unfilterJSON: function(filter) {
        if (filter) {
            return this.replace(filter, '$1');
        } else if (this.startsWith('/*-secure-') &&
                   this.endsWith('*/')) {
            return this.slice(10, -2);
        }
        return this;
    }
});

(Granted, this doesn't handle leading/trailing whitespace, but that could easily be added with strip(). Or, even better, don't handle it and simply demand that the input string doesn't have this whitespace.)

Using FF 3.5.6, with a 900 KB string, the stock prototypejs version of unfilterJSON() fails with a script stack space exhaustion error. This modified code handles this data just fine.