Why is ".map" slower then "while/for loop" in Dart(Flutter)

184

Solution 1

Can you explain that in detail?

It's like saying "I don't understand why hitchhiking on the back of a construction truck is so much slower than taking the high speed train to my destination".

The only detail that is important is that map is not a loop. map() internally probably uses a loop of some kind.

This person is misusing a method call that is meant for something else, just because a side-effect of that call when combining it with a call materializing the iterable, like toList(), is that it loops through the iterable given. It doesn't even have the side effect on it's own.

Stop reading "tutorials" or "tips" of people misusing language features. map() is not a loop. If you need a loop, use a loop. The same goes for the ternary operator. It's not an if, if you need an if, use it.

Use language features for what they are meant, stop misusing language features because their side-effect does what you want and then wondering why they don't work as well as the feature actually meant for it.

Sorry if this seems a bit ranty, but I have seen countless examples by now. I don't know where it comes from. My personal guess is "internet tutorials". Because everybody can write one. Please don't read them. Read a good book. It was written by professionals, proofread, edited, and checked. Internet tutorials are free, written by random people and about worth as much as they cost.

Solution 2

Its because mapping an array will create a copy of each value than modify the original array.

Since a while/for loop does not copy the values but rather just accesses them using their index, it is a lot faster.

Share:
184
Taz
Author by

Taz

Hi i'm developer :)

Updated on January 03, 2023

Comments

  • Taz
    Taz over 1 year

    I saw this article: https://itnext.io/comparing-darts-loops-which-is-the-fastest-731a03ad42a2

    It says that ".map" is slow with benchmark result

    But I don't understand why slower than while/for loop

    How does it work in low level?

    I think it's because .map is called an unnamed method like this (_){ }

    Can you explain that in detail?

  • jamesdlin
    jamesdlin about 2 years
    You also can infer that the time is dominated by constructing a new List and not from the anonymous function invocation by comparing the results from .map vs .forEach (which also uses a callback).
  • Taz
    Taz about 2 years
    You are right. That article is actually using .toList(), The inside map() is no different from the others loop Thanks!