I am working to improve performance of a function that takes an XML string and replaces certain characters (encoding) before returning the string. The function gets pounded, so it is important to run as quickly as possible. The USUAL case is that none of the characters are present - so I would like to especially optimize for that. As you will see in the sample code, the strings to be replaced are short, and relatively few. The source strings will often be short (e.g. 10-20 characters) but could be longer (e.g. 200 characters or so).
So far I have ensured that the regexes are precompiled and I've eliminated nested functions which slowed down operation (partial milliseconds matter at this point.)
var objXMLToString = new XMLToStringClass();
function XMLToStringClass(){
this.tester= /\\34|\\39|\\62|\\60|\\13\\10|\\09|\\92|&/;
this.replacements=[];
var self=this;
function init(){
var re = new regexReplacePair(/\\34/g,'"');
self.replacements.push(re);
re = new regexReplacePair(/\\39/g,"'");
self.replacements.push(re);
re = new regexReplacePair(/\\62/g,">");
self.replacements.push(re);
re = new regexReplacePair(/\\60/g,"<");
self.replacements.push(re);
re = new regexReplacePair(/\\13\\10/g,"\n");
self.replacements.push(re);
re = new regexReplacePair(/\\09/g,"\t");
self.replacements.push(re);
re = new regexReplacePair(/\\92/g,"\\");
self.replacements.push(re);
re = new regexReplacePair(/\&/g,"&");
self.replacements.push(re);
}
init();
}
function regexReplacePair(regex,replacementString){
this.regex = regex;
this.replacement = replacementString;
}
String.prototype.XMLToString = function() {
newString=this;
if(objXMLToString.tester.test(this)){
for (var x = 0;x<objXMLToString.replacements.length;x++){
newString=newString.replace(objXMLToString.replacements[x].regex,objXMLToString.replacements[x].replacement);
}
return newString;
}
return this;
}
- Is it possible that in this scenario
String.replace
functions will be better? - Currently I am replacing all characters if a single
character matches - is it possible
that testing and then conditionally
replacing would be better? If so, might
indexOf
be quicker than a regex for this dataset?