VelocityでStringをテンプレートとして読む時のパフォーマンス。
Apache Velocityで、テンプレートファイルを利用せずに、
Stringをテンプレートとして利用する方法を確認した。
方法1) Velocity#evaluateを使う。
Velocity.evaluate(new VelocityContext(map), writer, "test", templateString);
第四引数のtemplateStringが、テンプレートの文字列。
方法2) 自分でTemplateのインスタンスを作成する。
public Template newTemplate(String templateString) { RuntimeServices runtimeServices = RuntimeSingleton.getRuntimeServices(); StringReader reader = new StringReader(templateString); SimpleNode node; try { node = runtimeServices.parse(reader, "Template name"); } catch (ParseException e) { throw new RuntimeException("パースエラー", e); } Template template = new Template(); template.setRuntimeServices(runtimeServices); template.setData(node); template.initDocument(); return template; }
で、呼び出す方はこんな感じ。
Template template = newTemplate(templateString)
template.merge(new VelocityContext(map), writer);
パフォーマンス
ついでにパフォーマンスを手元のPCで計測してみたところ、
方法1) 10000回実施で、1400ms程度
方法2-a) 10000回実施で、1400ms程度(※Templateのインスタンスを毎回生成)
方法2-b) 10000回実施で、50ms程度(※Templateのインスタンスを使い回し)
という結果。
割と予想通り。
結論
毎回異なる文字列をテンプレートとして使うなら、
Velocity#evaluateが簡単で良い。
同じ文字列をテンプレートとして使う場合には、
Templateインスタンスを生成して使いまわした方が、数十倍早いヨ!