Created
November 18, 2016 06:17
-
-
Save KoryNunn/a9d532a9f910c97672de42244f8325f5 to your computer and use it in GitHub Desktop.
string templating perf tests, worth? MEEEHHHHHHHHHH!
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| var template = 'just your average string template using {type}', | |
| matchToken = /\{(.+?)\}/g; | |
| function compile(source){ | |
| var positions = {}, | |
| fnString = 'return "' + source.replace( | |
| matchToken, | |
| function(match, key) { | |
| return '" + (scope["' + key + '"] || "") + "'; | |
| } | |
| ) + '"'; | |
| return new Function('scope', fnString); | |
| } | |
| var compiled = compile(template); | |
| function compile2(source){ | |
| var parts = source.split(/\{.+?\}/g), | |
| indexs = {}, | |
| matcher = new RegExp(matchToken), | |
| next, | |
| index = 0; | |
| while(next = matcher.exec(source)){ | |
| indexs[index++] = next[1]; | |
| } | |
| return function(scope){ | |
| var result = parts[0], | |
| index = 0; | |
| while(index < parts.length - 1){ | |
| result += scope[indexs[index++]] + parts[index]; | |
| } | |
| return result; | |
| } | |
| } | |
| var compiled2 = compile2(template); | |
| function transform(source, scope){ | |
| return source.replace( | |
| matchToken, | |
| function(match, key) { | |
| return typeof scope[key] !== 'undefined' ? scope[key] : match; | |
| } | |
| ); | |
| } | |
| var start = Date.now(); | |
| console.log(compiled({type: 'x'})); | |
| for(var i = 0; i < 1000000; i++){ | |
| compiled({type: 'x'}); | |
| } | |
| console.log('new Function compiled:', Date.now() - start); | |
| var start = Date.now(); | |
| console.log(compiled2({type: 'y'})); | |
| for(var i = 0; i < 1000000; i++){ | |
| compiled2({type: 'x'}); | |
| } | |
| console.log('safe compiled:', Date.now() - start); | |
| var start = Date.now(); | |
| console.log(transform(template, {type: 'z'})); | |
| for(var i = 0; i < 1000000; i++){ | |
| transform(template, {type: 'x'}); | |
| } | |
| console.log('transform (string.replace internal):', Date.now() - start); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment