java - To compile or not to compile the pattern? -
i'm working on script code generator. created template script file, contains place holders few parameters , placeholders, should replaced real values during generation. replacement performed within loop(s). performance of generator kind of important (currently on java 7). dilemma follows:
do 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"; ... (int = 0; < sectioncount; i++) { // here... mastertmpl[i] = mastertmpl[i].replace(pholder_sect, somesectioncode); // else here... mastertmpl[i] = mastertmpl[i].replace(param_desc, desc) .replace(param_name, name) .replace(param_pid, pid) ... } or (the point being placeholders 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); ... (int = 0; < sectioncount; i++) { // here... mastertmpl[i] = this.regexsect.matcher(mastertmpl[i]).replaceall(matcher.quotereplacement(somesectioncode)); // 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 can measure execution, , stuff, i'm kind of hoping answer explains (un)importance of pattern compilation in particular case...
this code faster, finds occurrences of patterns in single search (instead of 1 per pattern); , importantly, replacements in single pass, instead of requiring 1 pass per pattern. building many strings expensive, because of copying , memory overhead - builds 1 fully-replaced string, in last line.
public static string replacemany(string input, map<string, string> replacements) { // build composite pattern replacement keys stringbuilder sb = new stringbuilder(); string prefix = ""; (string k : replacements.keyset()) { sb.append(prefix).append(pattern.quote(k)); prefix = "|"; } pattern p = pattern.compile(sb.tostring()); // replace in single loop matcher m = p.matcher(input); stringbuffer output = new stringbuffer(); while (m.find()) { // inspired http://stackoverflow.com/a/948381/15472 m.appendreplacement(output, ""); output.append(replacements.get(m.group(0))); } m.appendtail(output); return output.tostring(); }
Comments
Post a Comment