moleculerjs / moleculer

:rocket: Progressive microservices framework for Node.js
https://moleculer.services/
MIT License
6.07k stars 575 forks source link

[lodash] Remove usage of _.forIn #746

Open abdavid opened 4 years ago

abdavid commented 4 years ago

See #433 for context.

Describe the solution you'd like Remove usage of _.forIn throughout Moleculer.

Describe alternatives you've considered Alternatives:

// 1
for (variable of iterable) {
  statement
}

// 2
for (variable in object)
  statement

// 3
for await (variable of asyncIterable) {
  statement
}

... and a myriad of other natively supported patterns which could be used depending on the context.

Additional context https://github.com/moleculerjs/moleculer/search?q=_.forIn&unscoped_q=_.forIn

icebob commented 4 years ago

What is the difference between the first two alternatives?

By the way, we can't use the third because we don't use async/await in the core modules because await is slower then Promise, and performance is important in Moleculer :)

abdavid commented 4 years ago

What is the difference between the first two alternatives?

By the way, we can't use the third because we don't use async/await in the core modules because await is slower then Promise, and performance is important in Moleculer :)

Alternative 1 is for objects that implement the iterable interface. Arrays, strings etc

> for(const a of "abcdefg")
... console.log(a)
a
b
c
d
e
f
g
> for(const a of [1,2,3,4,5])
... console.log(a)
1
2
3
4
5
> for(const a of {a:1,b:2,c:3})
... console.log(a)
Thrown:
TypeError: {(intermediate value)(intermediate value)(intermediate value)} is not iterable

Alternative two is for "POJOs"

> for(const a in {a:1,b:2,c:3})
... console.log(a)
a
b
c
// for in with Iterables "a" is index.
> for(const a in [1,2,3,4,5])
... console.log(a)
0
1
2
3
4
abdavid commented 4 years ago

Some considerations aswell:

https://jsperf.com/for-of-vs-for-loop https://jsperf.com/for-vs-for-in

icebob commented 4 years ago

Yeah, the native for(;;) is the quickest, but we need to use better performance solution in the critical parts (action calling, event sending, transfer packets....etc).

So if there is a loop which processes something from the broker options only once at the startup, we can use any solution because it is not cut down the runtime performance.

Wallacy commented 4 years ago

BTW: https://v8.dev/blog/fast-async