i working on project needed pull list of excluded users out of giant list of user data. made me wonder if faster use double for loop
excluded id's in array
. or if putting id's in object properties , using .hasownproperty()
faster.
var mainlist = large json object of data. var earray = ["123456","234567","345678","456789","012345"]; var eobject = {"123456":"0","234567":"0","345678":"0","456789":"0","012345":"0"};
using double for loop
approach:
for(i=0; < mainlist.length; i++){ for(j=0; j < earray.length; j++){ if(mainlist[i]['id'] === earray[j]){ //do } } }
using .hasownproperty()
approach:
for(i=0; < mainlist.length; i++){ if(eobject.hasownproperty(mainlist[i]['id'])){ //do } }
i realize there other ways make loops faster, storing lengths in variables. i've tried simplify this.
thanks information.
if think it, make sense .hasownproperty()
approach faster because uses 1 for loop
.
wrong
i little surprised. expecting double loop slower. guess can't under estimate speed of for loop
.
double loop
while me seem slowest, ended being fastest benching @ 7,291,083 ops/sec
.hasownproperty()
i can see how slower because functions slower statements. benches @ 1,730,588 ops/sec
if..in
@geuis answer included if..in statement , thought test speed of seem fastest benching @ 2,715,091 ops/sec
still doesn't beat loops.
conclusion
for loops fast. double loops runs more 4 times faster using .hasownproperty()
, 3 times faster using if..in
condition. however, performance not noticeable; speed important have need complicate things. in opinion if..in
method way go.
test yourself in browser. using google chrome 28
.
Comments
Post a Comment