Data.Foldable `Maybe` instance mapM_ inlining and/or specialisation?
Motivation
Wisely, or otherwise, I've been using mapM_ action
as idiom that performs action input
given a Just input
value, and does nothing given a Nothing
value. I rather expected that all the abstractions involved are erased through inlining and specialisation, and that this would be a more concise and equivalent in cost variant of maybe (return ()) action
.
However, benchmarking this shows that the generated code is not the same in both cases. For trivial actions and input, measuring just the overhead, the mapM_
variant was ~1.5x slower. Is this expected? It seems that the Maybe
instance of Foldable
is not inlined in a manner that allows the code to be reduced to the logically equivalent maybe (return ()) action
form.
Proposal
If there are no downsides or obstacles, perhaps inline the foldr
instance of Maybe
, and, as appropriate, mapM_
and/or traverse_
. There are perhaps implementation constraints imposed by list fusion that I don't understand, so this is more of a question at this stage than a concrete proposal.
https://gitlab.haskell.org/ghc/ghc/-/blob/master/libraries/base/Data/Foldable.hs#L587-592 https://gitlab.haskell.org/ghc/ghc/-/blob/master/libraries/base/Data/Foldable.hs#L905-909 https://gitlab.haskell.org/ghc/ghc/-/blob/master/libraries/base/Data/Foldable.hs#L1181-1257
Cc: @hsyl20