Find vs First

Benchmark created by AmyAmy on


Preparation HTML

<script>
if (!Array.prototype.first) {
	/**
	 * Finds the first item in an array that satisfies a function, or the first item overall if no function is supplied.
	 * @param {function(*):Boolean} [fn] The function to use to find an item.
	 * @returns {*} An item from the array, or false if the array is empty or no matching item is found.
	 */
	Object.defineProperty(Array.prototype, "first", {
		value: function (/* fn */) {
			if (arguments.length === 0) {
				return this.length > 0 ? this[0] : false;
			}

			const fn = arguments[0];

			if (typeof fn !== "function") {
				throw new TypeError();
			}

			const t = Object(this);
			const len = t.length >>> 0;

			const thisArg = arguments.length >= 2 ? arguments[1] : void 0;

			for (let i = 0; i < len; i++) {
				if (i in t) {
					const res = fn.call(thisArg, t[i], i, t);
					if (res) {
						return t[i];
					}
				}
			}

			return false;
		}
	});
}
</script>

Setup

var arr = [{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }, { id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 },{ id: 1 }];

Test runner

Ready to run.

Testing in
TestOps/sec
First
arr.first(a => a.id === 5);
ready
Find
arr.find(a => a.id === 5);
ready

Revisions

You can edit these tests or add more tests to this page by appending /edit to the URL.

  • Revision 1: published by AmyAmy on