我正在尝试对模板框架进行一些评估。
对于简单的性能测试,我正在使用这些模板
private static String mvelTemplate = "Hello, my name is @{name},"
+ " @foreach{user : group.users} - @{user.id} - @{user.name} "
+ " @end{}";
private static String velocityTemplate = "Hello, my name is ${name},"
+ "#foreach($user in $group.users) - ${user.id} - ${user.name} #end " ;
private static String stringTemplate = "Hello, my name is <name>,"
+ "<group.users:{x| - <x.id> - <x.name>}> ";
// the group has 20 users
// 'Java' uses plain StringBuffer
Stringtemplate 的部分是
ST st = new ST(stringTemplate);
for (Map.Entry<String, Object> entry : vars.entrySet()) {
st.add(entry.getKey(),entry.getValue());
}
start = System.currentTimeMillis();
for (int n = 0; n < 10000; n ++) {
st.render();
}
end = System.currentTimeMillis();
结果是
Mvel.Compiled elapsed:68ms. ~147K per second
Velocity Cache elapsed:183ms. ~54K per second
StringTemplate elapsed:234ms. ~42K per second
Java elapsed:21ms. ~476K per second
由于我不知道字符串模板,这是我的问题:
StringTemplate 真的那么慢还是有其他(更快)的方式来渲染模板。
更新:
vars 看起来像这样:
Map<String,Object> vars = new HashMap<String,Object>();
Group g = new Group("group1");
for (int i = 0; i < 20; i++) {
g.addUser(new User(i, "user" + i));
}
vars.put("group", g);
vars.put("name", "john");
现在每个模板有 1.000.000 次迭代,并将整个基准测试循环 10 次
Mvel.Compiled elapsed:7056ms. ~141K per second
Velocity Cache elapsed:18239ms. ~54K per second
StringTemplate elapsed:22926ms. ~43K per second
Java elapsed:2182ms. ~458K per second