Created
February 17, 2014 04:57
-
-
Save popomore/9044989 to your computer and use it in GitHub Desktop.
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 bench = require('bench'); | |
var compare = {}; | |
var data = {}; | |
// 先安装 bench | |
// 10^5 基本小于 1 ms,所以对比 10^5 到 10^6 之间的数 | |
for (var i = 1; i <= 10; i++) { | |
var count = 100000 * i; | |
(function(count) { | |
var content = createContent(count); | |
compare['replace1 ' + count] = replace1.bind(null, content); | |
compare['replace2 ' + count] = replace2.bind(null, content); | |
})(count); | |
} | |
exports.compare = compare; | |
exports.done = done; | |
function replace1(content) { | |
var name = 'replace1 ' + content.length; | |
var begin = new Date().getTime(); | |
content.replace(/<\/(head|body)>/g, function(all, match) { | |
return match === 'head' ? 'h' : 'b' + all; | |
}); | |
var time = new Date().getTime() - begin; | |
save(name, time); | |
console.log(name + ' ' + time); | |
} | |
function replace2(content) { | |
var name = 'replace2 ' + content.length; | |
var begin = new Date().getTime(); | |
content.split('</head>').join('h</head>').split('</body>').join('b</body>'); | |
var time = new Date().getTime() - begin; | |
save(name, time); | |
console.log(name + ' ' + time); | |
} | |
function createContent(count) { | |
var head = '', body = ''; | |
while (count > 0) { | |
head += 'h'; | |
body += 'b'; | |
count--; | |
} | |
return '<html><head>' + head + '</head><body>' + body + '</body></html>'; | |
} | |
function save (name, time) { | |
if (!data[name]) data[name] = {value: 0, count: 0}; | |
data[name].value += time; | |
data[name].count++; | |
} | |
function done(d) { | |
bench.show(d); | |
console.log(''); | |
console.log(''); | |
Object.keys(data) | |
.sort(function(a, b) { | |
var a1 = a.split(' '); | |
var b1 = b.split(' '); | |
if (a1[0] !== b1[0]) { | |
return a1[0] > b1[0] ? 1 : -1; | |
} | |
return Number(a1[1]) - Number(b1[1]); | |
}) | |
.forEach(function(key) { | |
var o = data[key]; | |
console.log(key + ' ' + (o.value / o.count)); | |
}); | |
} | |
bench.runMain(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment