Skip to content

Instantly share code, notes, and snippets.

@YetAnotherMinion
Created June 10, 2017 15:45
Show Gist options
  • Save YetAnotherMinion/113b4741372d126b8128b1b40862df75 to your computer and use it in GitHub Desktop.
Save YetAnotherMinion/113b4741372d126b8128b1b40862df75 to your computer and use it in GitHub Desktop.
Benchmark mapping over an Array and collecting into a List
module IteratorBench exposing (main)
import Benchmark exposing (Benchmark, benchmark2)
import Benchmark.Runner exposing (BenchmarkProgram, program)
import Time
import Html exposing (Html, div, text)
import Array exposing (Array)
main : BenchmarkProgram
main =
program <|
Benchmark.describe "" <|
List.map
(Benchmark.withRuntime (Time.second * 5))
[ indexedMapBenchmarks
, mapBenchmarks
]
foo : (Int-> a -> b) -> a -> (Int, List b) -> (Int, List b)
foo func item (index, accumulator) =
(index + 1, func index item :: accumulator)
indexedMapToList : (Int -> a -> b) -> Array a -> List b
indexedMapToList func array =
Tuple.second <| Array.foldl (foo func) (0, []) array
mapToList : (a -> b) -> Array a -> List b
mapToList func array =
Array.foldl (\x acc-> func x :: acc ) [] array
smallTestData : Array Int
smallTestData =
Array.repeat 100 4
bigTestData : Array Int
bigTestData =
Array.repeat 10000 4
viewIndexedData : Int -> Int -> Html msg
viewIndexedData index item =
div [] [ text <| toString (index, item) ]
viewData : Int -> Html msg
viewData item =
div [] [ text <| toString item ]
indexedMapBenchmarks : Benchmark
indexedMapBenchmarks =
Benchmark.describe "indexedMap" <|
List.map
(Benchmark.withRuntime (Time.second * 5))
[ benchmark2 "small data: intermediate array" naiveIndexedMapToList viewIndexedData smallTestData
, benchmark2 "small data: fold" indexedMapToList viewIndexedData smallTestData
, benchmark2 "big data: create intermediate array" naiveIndexedMapToList viewIndexedData bigTestData
, benchmark2 "big data: use fold version" indexedMapToList viewIndexedData bigTestData
]
mapBenchmarks : Benchmark
mapBenchmarks =
Benchmark.describe "map" <|
List.map
(Benchmark.withRuntime (Time.second * 5))
[ benchmark2 "small data: create intermediate array" naiveMapToList viewIndexedData smallTestData
, benchmark2 "small data: fold" mapToList viewIndexedData smallTestData
, benchmark2 "big data: create intermediate array" naiveMapToList viewIndexedData bigTestData
, benchmark2 "big data: fold" mapToList viewIndexedData bigTestData
]
naiveIndexedMapToList : (Int -> a -> b) -> Array a -> List b
naiveIndexedMapToList func array =
Array.toList <| Array.indexedMap func array
naiveMapToList : (a -> b) -> Array a -> List b
naiveMapToList func array =
Array.toList <| Array.map func array
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment