arda,
@arda@micro.arda.pw avatar

Brain gymnastics: Which approach would work faster? And why?

#js #javascript #poll #object #programming

arda, (edited )
@arda@micro.arda.pw avatar

So here's the Poll !

#poll

teodorsandu,
@teodorsandu@mastodon.online avatar

@arda oh, and my answer would have been Approach 3: ['key1', 'key2'].every(itm => typeof(obj[itm]) !== 'undefined');

After running the benchmark i saw i was very close actually, 2nd fastest, almost as fast as the 'in' operator https://measurethat.net/Benchmarks/Show/977/0/undefined-vs-typeof-vs-in-vs-hasownproperty

So the fastest way is Approach 4: ['key1', 'key2'].every(itm => itm in obj);

arda,
@arda@micro.arda.pw avatar

@teodorsandu Ahh, didn't think about the in operator while posting. Nice one, thanks! I'd choose 4 now I seen it.

Between 1 and 2, I believe for every iteration since Object.keys() is regenerated, approach 1 would work faster.

teodorsandu,
@teodorsandu@mastodon.online avatar

@arda hasOwnProperty is right there with typeof, 'in' and double negation, its complexity must be O(1) as well. So yes, it definitely wins over anything that spends time creating and iterating over arrays.

arda,
@arda@micro.arda.pw avatar

@teodorsandu You actually benched this? Thanks, that's awesome!

I also wonder how the results would change if the compared fields (['key1', 'key2'] part) is huge.

teodorsandu,
@teodorsandu@mastodon.online avatar

@arda not exactly, i just added an equivalent, simplified version to the existing test i linked earlier. There's a Fork button you can use to add you own test cases.

teodorsandu,
@teodorsandu@mastodon.online avatar

@arda hint: you could actually Add a Poll, via the button next to the Attachments button which you used to upload the image.

arda,
@arda@micro.arda.pw avatar

@teodorsandu If photo is uploaded I cannot add a poll, also I wanted descriptions such as your last toot hence I didn't add a poll. I'll add a new reply as a poll. Cheers.

teodorsandu,
@teodorsandu@mastodon.online avatar

@arda well, we learn new things every day :) i never noticed that one button gets hidden once you use the other until you pointed it out - thanks! and sorry for the unnecessary suggestion

arda,
@arda@micro.arda.pw avatar

@teodorsandu No problems at all! We all learn/discover new things every day indeed 🙌

  • All
  • Subscribed
  • Moderated
  • Favorites
  • programming
  • DreamBathrooms
  • ngwrru68w68
  • modclub
  • magazineikmin
  • thenastyranch
  • rosin
  • khanakhh
  • InstantRegret
  • Youngstown
  • slotface
  • Durango
  • kavyap
  • mdbf
  • GTA5RPClips
  • provamag3
  • ethstaker
  • normalnudes
  • tester
  • osvaldo12
  • everett
  • cubers
  • tacticalgear
  • anitta
  • megavids
  • Leos
  • cisconetworking
  • JUstTest
  • lostlight
  • All magazines