Array loop vs foreach vs map with id compare in objects renan
Date tested:
one year ago
User agent:
Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/110.0.0.0 YaBrowser/23.3.3.709 Yowser/2.5 Safari/537.36
Test name
Executions per second
foreach
11844.7 Ops/sec
for
7690.5 Ops/sec
map
11458.4 Ops/sec
Benchmark definition (click to collapse):
Script Preparation code:
var idToGet = '' function uuidv4() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); } var arr = []; for (var i = 0; i < 1000; i++) { arr[i] = {id: uuidv4(), idx: i}; } var item = arr[Math.floor(Math.random() * arr.length)]; idToGet = item.id function someFn(i) { return i.id === idToGet }
Tests:
foreach
arr.forEach(function (item){ someFn(item); })
for
for (var i = 0, len = arr.length; i < len; i++) { someFn(arr[i]); }
map
arr.map(item => someFn(item))
Open this result on MeasureThat.net