我正在开发一个脚本代码生成器。我创建了一个模板脚本文件,其中包含少数参数和占位符的占位符,在生成过程中应该用实际值替换。在循环内执行替换。生成器的性能很重要(目前在Java 7上)。我的困境如下:
做这样的事情:
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)
...
}
或类似的东西(所有占位符都是符合的模式):
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));
...
}
我知道我可以测量执行和东西,但我有点希望得到一个答案来解释在这种特殊情况下模式编译的(非)重要性......
答案 0 :(得分:2)
此代码可能更快,因为它在单个搜索中找到模式的出现(而不是每个模式一个);最重要的是,在一次通过中完成所有替换,而不是每个模式需要一次通过。构建许多字符串有点昂贵,因为复制和内存开销 - 这在最后一行只构建了一个完全替换的字符串。
trim(preg_replace('/\s*\([^)]*\)/', '', 'Events (Road)')