Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in
/home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line
380
Warning: WP_Syntax::substituteToken(): Argument #1 ($match) must be passed by reference, value given in
/home/bateeqjg/public_html/news/wp-content/plugins/wp-syntax/wp-syntax.php on line
380
Warning: Undefined array key "layout" in
/home/bateeqjg/public_html/news/wp-content/plugins/wp-about-author/wp-about-author.php on line
94
Just for fun I decided to see if I could write a faster version of `Array.prototype.concat()`.
var concat = function (arr) {
var args = arguments,
len = args.length,
ArrayTypeOf = "[object Array]",
toString = Object.prototype.toString,
push = Array.prototype.push;
for (var i = 1; i < len; i++) {
if (toString.call(args[i]) === ArrayTypeOf) {
push.apply(arr, args[i]);
} else {
arr.push(args[i]);
}
}
return arr;
}; |
var concat = function (arr) {
var args = arguments,
len = args.length,
ArrayTypeOf = "[object Array]",
toString = Object.prototype.toString,
push = Array.prototype.push;
for (var i = 1; i < len; i++) {
if (toString.call(args[i]) === ArrayTypeOf) {
push.apply(arr, args[i]);
} else {
arr.push(args[i]);
}
}
return arr;
};
Benchmark Script.
console.time("native concat()");
for(var i = 0, len = 2020; i < len; i++) console.log( [].concat( new Array(1000).join("ax").split("") ).length );
console.timeEnd("native concat()");
console.time("custom concat()");
for(var i = 0, len = 2020; i < len; i++) console.log( concat( [], new Array(1000).join("ax").split("") ).length );
console.timeEnd("custom concat()"); |
console.time("native concat()");
for(var i = 0, len = 2020; i < len; i++) console.log( [].concat( new Array(1000).join("ax").split("") ).length );
console.timeEnd("native concat()");
console.time("custom concat()");
for(var i = 0, len = 2020; i < len; i++) console.log( concat( [], new Array(1000).join("ax").split("") ).length );
console.timeEnd("custom concat()");
Benchmark results:
native concat(): 386.000ms
custom concat(): 400.000ms
Well, I got quite close but didn’t surpass the raw power of native code.
Here are some other alternatives to concat but with limited functionality.
http://jsperf.com/concat-vs-push-apply/19