Is there any difference when using map or for loop inside a list in Dart?

171

Solution 1

In this specific case it won't change the end result.

However some functions on list, map included return a lazy Iterator. Which means that any computation that happens before the toList() will be made only on the necessary items.

In other words if you have a list of 100 elements and call myList.map(mappingFn).take(5).toList() the mapping function will be called only 5 times.

For example:

void main() {
  // mappingFn will be called 2 times
  [1,2,3,4,5].map(mappingFn).take(2).toList();
}

String mappingFn(int n) {
  print('called $n');
  return n.toString();
}

Solution 2

Yes, there is a significant difference in the performance.

comparison chart between for loop, while loop and map with different version

For more details see here

Share:
171
Fabián Bardecio
Author by

Fabián Bardecio

Updated on January 01, 2023

Comments

  • Fabián Bardecio
    Fabián Bardecio over 1 year

    I wasn't able to find an answer to this. Hope any of you can explain if there is any difference beyond that one of them looks prettier.

    Let's say I have a list of Strings (just an example, any list use case fits)

    final strings = ['string 1', 'string 2', 'string 3'];
    

    And I want to render those strings in some Text widgets.

    Doing it with a for loop, like this:

    Column(
      children: [
        for(final string in strings)
          Text(string),
      ],
    );
    

    Or doing it with map, like this:

    Column(
        children: strings.map((String string) => Text(string)).toList()
    );
    

    Is there any difference in performance or something else?

    • sinanspd
      sinanspd over 2 years
      The short answer is yes. Technically map is a tad slower but in reality there is no chance your application will scale to a point where it is noticeable at all. Flutter will choke long before you reach that point. I always prefer map because it preserves functional composition and easier to read imo