Nesse artigo, veremos a performance para percorrermos uma lista simples utilizando diferentes formas.
Criando um array numérico
Na primeira "bateria" de testes, iremos criar um simples array com valor numérico para validarmos o tempo que levamos para percorrer:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
let array = Array(repeating: 0, count: 10000) |
Criamos um array com valores iguais e tamanho 10.000, não estamos preocupados em relação ao espaço de memória em uma lista, por isso, criamos de forma simples.
Percorrendo o array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
let array = Array(repeating: 0, count: 10000) | |
var start = CFAbsoluteTimeGetCurrent() | |
for _ in array { } | |
var end = CFAbsoluteTimeGetCurrent() | |
print("for in -> \(end - start) seconds") | |
start = CFAbsoluteTimeGetCurrent() | |
_ = array.map { $0 } | |
end = CFAbsoluteTimeGetCurrent() | |
print("map -> \(end - start) seconds") | |
start = CFAbsoluteTimeGetCurrent() | |
_ = array.filter({ _ in return true }) | |
end = CFAbsoluteTimeGetCurrent() | |
print("filter -> \(end - start) seconds") | |
start = CFAbsoluteTimeGetCurrent() | |
_ = array.compactMap { $0 } | |
end = CFAbsoluteTimeGetCurrent() | |
print("compactMap -> \(end - start) seconds") | |
start = CFAbsoluteTimeGetCurrent() | |
_ = array.flatMap{ $0 } // Deprecated | |
end = CFAbsoluteTimeGetCurrent() | |
print("flatMap -> \(end - start) seconds") |