Is using single for-loop faster than chained higher-order functions?

2109 views swift
1

Consider that we have an array of Ints:

let ints = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

We want get a new array based on ints as follows:

  • Filter the values, where the element must be more than 4.
  • Map the values to strings, as "this is (the element multiplied by 2)"

So, we can achieve it -using Swift- like this:

let strings = ints.filter { $0 > 4 }.map { "this is \($0 * 2)" }

However, at this point there are 2 iterations happened (filter and map). Based on our example, filter checks 10 elements, and map checks 6 elements (filtered result), which means it takes 16 iterations to generate strings array.

However, using a standard for-in loop as:

var strings2: [String] = []

for int in ints {
    if int > 4 {
        strings2.append("this is \(int * 2)")
    }
}

should give the exact same result when using the filter and map functions with 10 iterations instead.

For this case, regardless of the importance of code readability, is the choice of using for-in better?

answered question

What are the results of your performance tests? Is the difference enough to matter to your app? Make sure your tests are done in a real app built with optimizations enabled. Never test performance in the playground.

@rmaddy the difference trivial. However, the good thing is to note that using a for-in loop might me better, is it correct?

1 Answer

1

You can achieve the result with one iteration with similar readability.

let strings = ints.compactMap { $0 > 4 ? "this is \($0 * 2)" : nil }

posted this

Have an answer?

JD

Please login first before posting an answer.