Skip to content

Commit

Permalink
Use string concatenation to build the output string
Browse files Browse the repository at this point in the history
Switching from pushing to an array and using .join() to using simple string concatenation yields performance gains up to 260%.
  • Loading branch information
nwoltman committed Oct 31, 2019
1 parent da51ca3 commit 4434314
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 3 deletions.
3 changes: 2 additions & 1 deletion benchmark/bench-ejs.js
@@ -1,8 +1,9 @@
'use strict';

var ejs = require('..');
var path = require('path');

ejs.fileLoader = function(n) { return files[n.replace(/^\//, '').replace(/\.ejs$/, '')]; };
ejs.fileLoader = function(n) { return files[path.basename(n, '.ejs')]; };

var loops = 10000;
var runs = 9; // min 4 for median
Expand Down
6 changes: 4 additions & 2 deletions lib/ejs.js
Expand Up @@ -572,7 +572,9 @@ Template.prototype = {

if (!this.source) {
this.generateSource();
prepended += ' var __output = [], __append = __output.push.bind(__output);' + '\n';
prepended +=
' var __output = "";\n' +
' function __append(s) { if (s !== undefined && s !== null) __output += s }\n';
if (opts.outputFunctionName) {
prepended += ' var ' + opts.outputFunctionName + ' = __append;' + '\n';
}
Expand All @@ -591,7 +593,7 @@ Template.prototype = {
prepended += ' with (' + opts.localsName + ' || {}) {' + '\n';
appended += ' }' + '\n';
}
appended += ' return __output.join("");' + '\n';
appended += ' return __output;' + '\n';
this.source = prepended + this.source + appended;
}

Expand Down

0 comments on commit 4434314

Please sign in to comment.