String.format loop vs regex

Benchmark created on


Setup

function format(pattern, context) {
        var value = '';
        var i = 0;
        
        while (true) {
            var open = pattern.indexOf('{', i);
            var close = pattern.indexOf('}', i);
            
            if (open < 0 && close < 0) {
                value += pattern.slice(i);
                break;
            } else if (close > 0 && (close < open || open < 0)) {
                if (pattern.charAt(close + 1) !== '}') {
                    throw 'stringFormatBraceMismatch';
                }
                
                value += pattern.slice(i, close + 1);
                i = close + 2;
                continue;
            }
            
            value += pattern.slice(i, open);
            i = open + 1;
        
            if (value.charAt(i) === '{') {
                value += '{';
                i++;
                continue;
            } else if (close < 0) {
                throw 'stringFormatBraceMismatch';
            }
            
            var name = pattern.substring(i, close);
            value += context[name];
            i = close + 1;
        }
        
        return value;
    }
    
    function format_r(pattern, context) {
        return pattern.replace(/\{[^\}]+\}/, function(match) {
            return context[match.slice(1, -1)];
        });
    }

Test runner

Ready to run.

Testing in
TestOps/sec
replacing using loop
format('Hello {0}!', ['world']);
format('Hello {world}!', {world: 'world'});
format('{0} {1}!', ['Hello', 'world']);
format('{hello} {world}!', {hello: 'Hello', world: 'world'});
format('{0} foo {1} foo {2} foo {3} foo {4}', ['bar', 'bar', 'bar', 'bar', 'bar']);
ready
replacing using regular expression
format_r('Hello {0}!', ['world']);
format_r('Hello {world}!', {world: 'world'});
format_r('{0} {1}!', ['Hello', 'world']);
format_r('{hello} {world}!', {hello: 'Hello', world: 'world'});
format_r('{0} foo {1} foo {2} foo {3} foo {4}', ['bar', 'bar', 'bar', 'bar', 'bar']);
ready

Revisions

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