From 4434314d53460cff35dba9ec6819aa112bcb7a7a Mon Sep 17 00:00:00 2001 From: Nathan Woltman Date: Wed, 30 Oct 2019 22:17:37 -0400 Subject: [PATCH] Use string concatenation to build the output string Switching from pushing to an array and using .join() to using simple string concatenation yields performance gains up to 260%. --- benchmark/bench-ejs.js | 3 ++- lib/ejs.js | 6 ++++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/benchmark/bench-ejs.js b/benchmark/bench-ejs.js index 6a93cf5a..b44f5471 100755 --- a/benchmark/bench-ejs.js +++ b/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 diff --git a/lib/ejs.js b/lib/ejs.js index 571c79f7..51b202e6 100755 --- a/lib/ejs.js +++ b/lib/ejs.js @@ -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'; } @@ -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; }