I'm working on a script code generator. I created a template script file, which contains place holders for few parameters and placeholders, that should be replaced with real values during generation. Replacement is performed within the loop(s). Performance of the generator is kind of important (currently on Java 7). My dilemma as follows:
Do something like this:
private final String PHOLDER_SECT = "#__PHOLD_SECT__#";
private final String PARAM_PID = "__param_pid";
private final String PARAM_NAME = "__param_name";
private final String PARAM_DESC = "__param_desc";
...
for (int i = 0; i < sectionCount; i++) {
// do something here...
masterTmpl[i] = masterTmpl[i].replace(PHOLDER_SECT, someSectionCode);
// something else here...
masterTmpl[i] = masterTmpl[i].replace(PARAM_DESC, desc)
.replace(PARAM_NAME, name)
.replace(PARAM_PID, pid)
...
}
or something like this (the point being all placeholders are complied patterns):
private final Pattern regexSect = Pattern.compile("#__PHOLD_SECT__#", Pattern.LITERAL);
private final Pattern regexPid = Pattern.compile("__param_pid", Pattern.LITERAL);
private final Pattern regexName = Pattern.compile("__param_name", Pattern.LITERAL);
private final Pattern regexDesc = Pattern.compile("__param_desc", Pattern.LITERAL);
...
for (int i = 0; i < sectionCount; i++) {
// do something here...
masterTmpl[i] = this.regexSect.matcher(masterTmpl[i]).replaceAll(Matcher.quoteReplacement(someSectionCode));
// something else here...
masterTmpl[i] = this.regexDesc.matcher(masterTmpl[i]).replaceAll(Matcher.quoteReplacement(desc));
masterTmpl[i] = this.regexName.matcher(masterTmpl[i]).replaceAll(Matcher.quoteReplacement(name));
...
}
I know that I can measure execution, and stuff, but I'm kind of hoping for an answer that explains the (un)importance of pattern compilation in this particular case...