Flutter Benchmark Tuesday: for loop vs .map() — which one is faster?

Alex Josef Bigler
Full Struggle Developer
4 min readApr 18, 2023

In one of my old articles (check here 👈), I demonstrated deserialization of JSON into an object, and many people noticed that I used a for loop for an array, although it is easier to use map() method. I also criticized zoomers who use code generators that utilize the map() method instead of a for loop 🤙.

Well, it’s time to understand which is better: map() or for, and we will do this with the help of benchmarks.

C’mon, let’s go

We will be using the benchmarking library.

Unfortunately, these benchmarks may not be what you are used to in backend languages. All we can see is the execution time, but that should be enough for our purposes.

Okay, I want to see which is better for iterating through array elements — using a for loop or using map().

Let’s do it with a test. We are all big boyz here and we know how to do things in an app without using widgets (If you want to join our community, you can read an article about unit tests here 👈).

Create a file called benchmark_test.dart and put it in the test folder:

Lines 9, 12, 14 — we obtain an array from JSON.

Line 18 — the first measurement — we iterate through the elements using a for loop.

Line 23— the second measurement — we iterate through the elements using map() method.

Run the test, then we see the result:

Both loops are running too fast.

BUT!

We can still see the difference, and the result surprised me. In 2 seconds, map ran 8 times more often. Therefore, the map method is 8 times faster…

I apologize to the zoomers, I spoke too harshly. I will review all of my code 😳. *** Actually no ***

That’s about it

Very often it seems like this doesn’t matter — everything works fast enough, why make it even faster? But if we look at this example through the lens of real life — imagine you have a cafe that can serve either 6 million people per day or 48 million. Which one would you choose? Write it in the comments.

Subscribe so you don’t miss any new groundbreaking posts.

You might also be interested in my other benchmarks:

Investing stuff:

Tech stuff:

Or a whole series of articles about working with REST API (it’s a real shit like Santa Barbara):

--

--

Alex Josef Bigler
Full Struggle Developer

Enthusiast of new technologies, entrepreneur, and researcher. Writing about IT, economics, and other stuff. Exploring the world through the lens of data.