elm / core

Elm's core libraries
http://package.elm-lang.org/packages/elm/core/latest
BSD 3-Clause "New" or "Revised" License
2.8k stars 359 forks source link

List.map foldl-version #1116

Open andre-dietrich opened 3 years ago

andre-dietrich commented 3 years ago

Hi, i just did some experiments with List.map and a foldl version of it, which seems to be faster (on average 25%), for different sizes and also when multiple mapping operations are applied subsequently within a pipe.

map f =
    List.foldl (\x acc -> (::) (f x) acc) []
        >> List.reverse

See the benchmark

ezgif com-gif-maker

Maybe this is an optimization option, next to a native Kernel-function ...

github-actions[bot] commented 3 years ago

Thanks for reporting this! To set expectations:

Finally, please be patient with the core team. They are trying their best with limited resources.

andre-dietrich commented 3 years ago

Only for curiosity, I added a local List.map1 function that does the same as List.map but it uses a Kernel function ... The patches look like this:

-- ~/.elm/0.19.1/packages/elm/core/1.0.5/src/List.elm

...

map1 : (a -> result) -> List a -> List result
map1 =
  Elm.Kernel.List.map1

...
// ~/elm/0.19.1/packages/elm/core/1.0.5/src/Elm/Kernel/List.js

...

var _List_map1 = F2(function(f, xs)
{
    for (var arr = []; xs.b ; xs = xs.b) // WHILE_CONSES
    {
        arr.push(f(xs.a));
    }
    return _List_fromArray(arr);
});

...

And boom, on Chromium I got a performance boost up to 250%, seems to be constant, tested for list lengths from 5 to 5000 ... On Firefox, the results seem to be similar, however it is dropping from 250% to 60% on lists with a 5000 elements...

screenshot_10

screenshot_1000