For clarification, let's review the following example:
Consider that we have the following array of Ints:
let array = [1, 2, 3, 4, 5]
and we've been asked to generate a new array from array
corresponding to the following two conditions:
- The element in
array
should be > 3. - The new generated element should be a string instead of int, as: "this is (element * 2)".
By following the approach of chaining higher order functions, we could achieve it like this:
let newArray = array.filter { $0 > 3 }.map { "This is \($0 * 2)" }
At this point, it should iterate through all elements for filter
and then reiterate once again through the filtered elements for the map
.
However, when doing it using standard for-loop
:
var transformed = [String]()
for i in 0..<array.count {
if array[i] > 3 {
transformed.append("This is \(array[i] * 2)")
}
}
it should iterate through array
elements for only one time.
AFAIK, on the other hand, using higher order functions leads to get rid of mutability (we declared newArray
as let
instead of var
).
In such a case, what would be better for dealing with performance?