nomiddlename/log4js-node — Issue #58: Performance Analysis.
Author: satyamshekhar
Created: 2012-02-04 10:46:53+00:00
State: open

I did some tests to see how efficient the regex replace method is to format strings (https://github.com/nomiddlename/log4js-node/blob/master/lib/layouts.js#L31).

According to the tests I did simple string concatenation is much faster that regex replace method - around 3.5 times.

Here are the results:

stringAdd time: 36
stringAdd memory: { rss: 9277440, heapTotal: 3910080, heapUsed: 1682956 }

regex time: 117
regex memory: { rss: 9211904, heapTotal: 3926400, heapUsed: 1914876 }

```javascript

var format = "%s %s some data string to: %s";
var a = "adfkjafgksjgfksjsgkjsf;gjsgfjs;fdg";
var b = "jadfjadfhjadfkjadfkjakdfjadkfjakdfjakfj";
var c = 5;

var NTIMES = 100000;

// use each test seperately - to test memory.

regexTest();
// arrayJoinTest();
// stringAddTest();

function regexTest() {
var data = [a, b, c];
var s = new Date();
for (var i = 0; i < NTIMES; i++) {
var k = 0;
var str = format.replace(/%[sdj]/g, function (match) {
switch (match) {
case "%s": return new String(data[k++]);
case "%d": return new Number(data[k++]);
case "%j": return JSON.stringify(data[k++]);
default:
return match;
}
});
}
var e = new Date();
console.log("regex time: %s", e - s);
console.log("regex memory: %s", require("util").inspect(process.memoryUsage()));
}

function stringAddTest() {
var data = [a, b, c];
var s = new Date();
for (var i = 0; i < NTIMES; i++) {
f = format.split("%s");
str = "";
for (var j = 0, len = f.length - 1; j < len; j++) {
str += f[j];
str += data[j];
}
str += f[f.length - 1];
}
var e = new Date();
console.log("stringAdd time: %s", e - s);
console.log("stringAdd memory: %s", require("util").inspect(process.memoryUsage()));
}

function arrayJoinTest() {
var data = [a, b, c];
var s = new Date();
var arr = [ ];
for (var i = 0; i < NTIMES; i++) {
f = format.split("%s");
str = "";
for (var j = 0, len = f.length - 1; j < len; j++) {
arr.push(f[j]);
arr.push(data[j]);
}
arr.push(f[f.length - 1]);
arr.join("");
}
var e = new Date();
console.log("arrayJoin time: %s", e - s);
console.log("arrayJoin memory: %s", require("util").inspect(process.memoryUsage()));
}