Skip to content

Instantly share code, notes, and snippets.

@kraklin
Last active April 2, 2019 09:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kraklin/261c86eafa7e4591f6ddf55f15f2d956 to your computer and use it in GitHub Desktop.
Save kraklin/261c86eafa7e4591f6ddf55f15f2d956 to your computer and use it in GitHub Desktop.
Benchmark of pattern matching vs. List.indexedMap
module BenchmarkPattern exposing (main)
import Benchmark exposing (..)
import Benchmark.Runner exposing (BenchmarkProgram, program)
main : BenchmarkProgram
main =
program suite
suite : Benchmark
suite =
let
sampleList : List Int
sampleList =
List.range 0 100
|> List.map (\item -> ( item, List.range 0 10 ))
addOne : Int -> Int
addOne =
(+) 1
addOneExceptForFirstPatternMatch : List Int -> List Int
addOneExceptForFirstPatternMatch list =
case list of
[] ->
[]
head :: tail ->
head :: List.map addOne tail
patternMatch : List ( Int, List Int ) -> List ( Int, List Int )
patternMatch list =
case list of
[] ->
[]
head :: tail ->
Tuple.mapSecond addOneExceptForFirstPatternMatch head :: List.map (Tuple.mapSecond (List.map addOne)) tail
addOneExceptForFirstIndexedMap : List Int -> List Int
addOneExceptForFirstIndexedMap =
List.indexedMap
(\i item ->
if i == 0 then
item
else
addOne item
)
indexedMap : List ( Int, List Int ) -> List ( Int, List Int )
indexedMap =
List.indexedMap
(\i tuple ->
if i == 0 then
Tuple.mapSecond addOneExceptForFirstIndexedMap tuple
else
Tuple.mapSecond (List.map addOne) tuple
)
in
describe ""
[ -- nest as many descriptions as you like
Benchmark.compare "Pattern matching vs. indexedMap"
"Pattern Match"
(\_ -> patternMatch sampleList)
"indexedMap"
(\_ -> indexedMap sampleList)
]

Benchmark Report

pattern matching vs. indexedMap

name runs / second % change goodness of fit
Pattern Match 12,168 - 99.74%
indexedMap 12,284 +0.95% 99.86%
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment