Slow Javascript Replace

I ran into situation the other day where I had been doing a Javascript “Replace” function on a string of text. The Javascript replace looked intriguing because I could use a regular expression and have it replaced with a give string through an entire text. The product requirements insisted that this would only be a few KB of text at any given time. So, we implemented the replace, ran some tests and went live.

It didn’t take long, however, before we started running into huge performance issues on the instance. When we tracked it down, we found that the end user was sending in data in the size of MB and that while the Javascript replace function performed just fine for a few hundred KB, it’s response time grew exponentially with the bigger string sizes. A 1.5MB string was taking over 10 minutes to perform the replace.

At this point, we decided to convert the string to a Java string object through ServiceNow’s package calls.

1
2
3
4
var String= Packages.java.lang.String;
mystring = new String("Goingotogotothegonewiththewindmovie");
mystring = mystring.replace("go","##");
gs.log("MYSTRING: " + mystring);

Once I did this, the replace mechanism took only milliseconds on even the larger files.