RegEx-templating (v9)

Revision 9 of this benchmark created by Martin Reurings on


Description

A performance test to measure the impact of how regular expressions are used in a templating system. A final line-up of the original candidates against the most viable alternative.

Preparation HTML

<script>
  var data1 = {
    "test1": "value1",
    "test2": "value2",
    "test3": "value3"
  }

  var template1 = "This is {test1} to see how fast different {test2}-replacement techniques perform! ({test3})";
  var re1 = /{([^}]+)}/gi;
</script>

Test runner

Ready to run.

Testing in
TestOps/sec
Dynamic Regular Expressions
var template = template1;
for (var i in data1) {
  template = template.replace(new RegExp('{' + i + '}', 'g'), data1[i]);
}
ready
Static Regular Expression
var o = template1;
var re = /{([^}]+)}/gi;
var m;
while (m = re.exec(o)) {
  o = RegExp.leftContext;
  o += data1[m[1]];
  o += RegExp.rightContext;
  re.test("");
}
ready
Static RE, proper String append
var o = "",
    m = null,
    preIndex = 0;
while (m = re1.exec(template1)) {
  o += RegExp.leftContext.substr(preIndex) + data1[m[1]];
  preIndex = re1.lastIndex;
}
o += RegExp.rightContext;
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by Martin Reurings on
  • Revision 2: published by Martin Reurings on
  • Revision 3: published by Martin Reurings on
  • Revision 4: published on
  • Revision 5: published by Martin Reurings on
  • Revision 6: published on
  • Revision 7: published on
  • Revision 9: published by Martin Reurings on