<!doctype html>
<meta charset=utf-8>
<title>Concat test</title>
<p>View output in console ...</p>
<script>
(function () {
var _nativeJoin = Array.prototype.join;
var _concatJoin = function (glue) {
var result = '';
for(var i = 0, l = this.length; i < l; i++) {
result += glue + this[i];
}
return result;
};
// is firefox, chrome use concat join
// Dirty hack
if (navigator.userAgent.indexOf("Chrome") > -1 || navigator.userAgent.indexOf("Firefox") > -1) {
Array.prototype.join = _concatJoin;
Array.prototype._join = _nativeJoin;
}
/**/
// Main test part
// helper
function randomString(length) {
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz'.split('');
if (! length) {
length = Math.floor(Math.random() * chars.length);
}
var str = '';
for (var i = 0; i < length; i++) {
str += chars[Math.floor(Math.random() * chars.length)];
}
return str;
}
// Generate array
var source = [];
for (var n = 1; n <= 100000; n++) {
source.push(randomString());
}
// + Version
console.time('concat "+"');
var str1 = '';
for(var i = 0, l = source.length; i < l; i++) {
str1 += source[i];
}
console.timeEnd('concat "+"');
// Current Array.join()
if (!Array.prototype._join) {
console.log('Native join');
} else {
console.log('Concat join');
}
console.time('Current Array.join()');
var str2 = source.join("");
console.timeEnd('Current Array.join()');
if (Array.prototype._join) {
// Native Join Version
console.time('native "join" // fallback');
var str3 = source._join("");
console.timeEnd('native "join" // fallback');
} else {
console.log('no fallback');
}
// Debug
console.log(str1 == str2);
console.log(str2 == str3);
})();
</script>