Skip to content

Instantly share code, notes, and snippets.

@peacememories
Last active January 11, 2018 22:54
Show Gist options
  • Save peacememories/4d33a82a5b8734eb752ea8cdcca79c5c to your computer and use it in GitHub Desktop.
Save peacememories/4d33a82a5b8734eb752ea8cdcca79c5c to your computer and use it in GitHub Desktop.
elm-lazy-list drop benchmark
{
"version": "1.0.0",
"summary": "helpful summary of your project, less than 80 characters",
"repository": "https://github.com/user/project.git",
"license": "BSD3",
"source-directories": [
"."
],
"exposed-modules": [],
"dependencies": {
"BrianHicks/elm-benchmark": "2.0.3 <= v < 3.0.0",
"eeue56/elm-lazy": "1.0.0 <= v < 2.0.0",
"eeue56/elm-lazy-list": "1.0.0 <= v < 2.0.0",
"elm-lang/core": "5.1.1 <= v < 6.0.0",
"elm-lang/html": "2.0.0 <= v < 3.0.0"
},
"elm-version": "0.18.0 <= v < 0.19.0"
}
module Main exposing (..)
import Benchmark exposing (..)
import Benchmark.Runner exposing (BenchmarkProgram, program)
import Lazy exposing (Lazy)
import Lazy.List exposing (LazyList)
{-| Comparing the replacement `drop` with the original, performance-wise
-}
suite : Benchmark
suite =
let
testList =
Lazy.List.numbers
numberToDrop =
500
-- much more than this and chrome stackoverflows with the lib version
in
describe "Lazy.List"
[ Benchmark.compare "drop"
"library"
(\_ ->
Lazy.List.drop numberToDrop testList
|> Lazy.List.head
)
"replacement"
(\_ ->
customDrop numberToDrop testList
|> Lazy.List.head
)
]
{-| Replacement for `Lazy.List.drop`
The original `Lazy.List.drop` fails causes a stackoverflow when dropping too many elements because the recursion cannot be optimized away. This new version uses an inner function which can be optimized and, as far as I can tell, eliminates the change of stack overflows at least in this department.
-}
customDrop : Int -> LazyList a -> LazyList a
customDrop num list =
let
dropHelper num list =
if num <= 0 then
Lazy.force list
else
case Lazy.force list of
Lazy.List.Nil ->
Lazy.List.Nil
Lazy.List.Cons _ rest ->
dropHelper (num - 1) rest
in
Lazy.lazy
(\() ->
dropHelper num list
)
main : BenchmarkProgram
main =
program suite
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment