Categories: Frontend Tech

Re-implementation of Javascript’s Array.prototype.concat()

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;
};

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()");

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

Larry Battle

I love to program, and discover new tech. Check out my stackoverflow and github accounts.

Share
Published by
Larry Battle

Recent Posts

What really is Data Science? Told by a Data Scientist

What REALLY is Data Science? Told by a Data Scientist - By Joma Tech

7 years ago

Video: How Water Towers Work

How Water Towers Work - Practical Engineering

7 years ago

Dev Tip: Simple tips to improve code reviews

Writing perfect code is a challenging process. That's where code reviews come in to help…

7 years ago

Video: How AI will change the 3d industry

"The Next Leap: How A.I. will change the 3D industry - Andrew Price - Blender"

7 years ago

Best Software Presentation for 2018

"Captain Disillusion: World's Greatest Blenderer - Live at the Blender Conference 2018 - CaptainDisillusion"

7 years ago

Dev Video: A Few Linux Shell Tips

My 5 Favorite Linux Shell Tricks for SPEEEEEED (and efficiency) - By tutoriaLinux > What's…

7 years ago