string interpolation: or vs ref?:

JavaScript performance comparison

Revision 2 of this test case created by queue

Info

For string templating, which style is best for replacing undefined values with ''?

Preparation code

 
<script>
Benchmark.prototype.setup = function() {
    var data1 = {
      a: 'this',
      b: 'is',
      c: 'a',
      d: void 0,
      e: 'test'
    }
   
    var data2 = {
      a: 'this',
      b: 'is',
      c: 'a',
      d: 'cool',
      e: 'test'
    }
   
    function orTemplate(o) {
      return '<p>' + o.a + ' ' + o.b + ' ' + o.c + ' ' + (o.d || '') + ' ' + o.e + '.</p>'
    }
   
    function ternaryTemplate(o) {
      var $ref
      return '<p>' + o.a + ' ' + o.b + ' ' + o.c + ' ' + (($ref = o.d) ? $ref : '') + ' ' + o.e + '.</p>'
    }
   
    function joinTemplate(o) {
      var $ref, buf = ['<p>', o.a, ' ', o.b, ' ', o.c, ' ']
      if ($ref = o.d) {
        buf.push($ref)
      }
      buf.push(' ', o.e, '.</p>')
      return buf.join('')
    }
   
    function conditionalTemplate(o) {
      var buf1 = '<p>' + o.a + ' ' + o.b + ' ' + o.c + ' '
      var buf2 = ' ' + o.e + '.</p>'
      var $ref
      if ($ref = o.d) {
        return buf1 + $ref + buf2
      } else {
        return buf1 + buf2
      }
    }
   
};
</script>

Test runner

Warning! For accurate results, please disable Firebug before running the tests. (Why?)

Java applet disabled.

Testing in unknown unknown
Test Ops/sec
or
orTemplate(data1)
orTemplate(data2)
pending…
ref?:
ternaryTemplate(data1)
ternaryTemplate(data2)
pending…
Array conditional push
joinTemplate(data1)
joinTemplate(data2)
pending…
Conditional concat
conditionalTemplate(data1)
conditionalTemplate(data2)
pending…

Compare results of other browsers

Revisions

You can edit these tests or add even more tests to this page by appending /edit to the URL. Here’s a list of current revisions for this page:

0 comments

Add a comment