Performance tips
ExtendScript Perf. | Given obj={k1:null,k2:null,etc.} and re=/k1|k2|etc/ obj.hasOwnProperty("foo") is about 10X faster than re.test("foo")
Using redraw = false can make a big difference.
app.scriptPreferences.enableRedraw = false;
Depending on the version of indesign that you are working with however you can try and use the FAST_ENTIRE_SCRIPT undo mode as long as you set your grep outside this FAST_ENTIRE... mode.
ExtendScript Toolkit Unbearably Slow? by Kriss Coppiters — explains why you shouldn´t abuse global variables.
“Writing code like a story” by Kriss Coppiters
Performance Optimizations for High Speed JavaScript
ExtendScript Memory by Marc Autret (for script developers only)