Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is searching for a value in an object by key slower than using 'for in' in js?

Why is it slower to search for a value in an object by key than using for in in JavaScript?

Like this code:

const a = { a: { txt: 1 }, b: { txt: 2 }, c: { txt: 3 }, d: { txt: 4 }, e: { txt: 5 }, f: { txt: 6 } };    console.time('1');  let n = a['e'].txt;  console.log(n, '<<n')  console.timeEnd('1');    console.time('2');  for (const key in a) {      if (a[key].txt == 5) {          const m = a[key];          console.log(m, '<<m')          break;      }  }  console.timeEnd('2');

The result is

 5 '<<by key' 1: 2.329ms { txt: 5 } '<<for in ' 2: 0.447ms 

Isn't this weird?

like image 668
Feng Yujia Avatar asked Mar 14 '19 07:03

Feng Yujia


2 Answers

This is because of how the JIT compiler works.

When you start a JS script with Node, the V8 starts interpreting it, while compiling it into native machine code.

Running it in the Chrome Devtools console, I get this output :

5 "<<n" 0.167724609375ms {txt: 5} "<<m" 2: 0.262939453125ms 

NodeJS output :

5 '<<n' 1: 18.684ms { txt: 5 } '<<m' 2: 3.713ms 

But when inverting the 2 variations :

const a = { a: { txt: 1 }, b: { txt: 2 }, c: { txt: 3 }, d: { txt: 4 }, e: { txt: 5 }, f: { txt: 6 } };   console.time('2'); for (const key in a) {     if (a[key].txt = 5) {         const m = a[key];         console.log(m, '<<m')         break;     } }  console.timeEnd('2'); console.time('1'); let n = a['e'].txt; console.log(n, '<<n') console.timeEnd('1'); 

Output :

{ txt: 5 } '<<m' 2: 22.017ms 5 '<<n' 1: 0.245ms 

As you can see, the version that is executed first takes much more time than the second.

However, if you average it, you can see that executing the key access is much faster than the for in loop.

like image 115
Seblor Avatar answered Oct 14 '22 23:10

Seblor


You have an error in your program

if (a[key].txt = 5) 

You are not checking if the txt property is equal to 5. You are setting the property to 5 which means you are finished after the first execution of the loop regardless.

like image 40
MasterCassim Avatar answered Oct 14 '22 23:10

MasterCassim