# StateT performance benchmarks?

**URL:** <https://discourse.haskell.org/t/statet-performance-benchmarks/7439>\
**Category:** Learn\
**Created:** [August 27, 2023, 5:57am UTC](https://discourse.haskell.org/t/statet-performance-benchmarks/7439 "2023-08-27T05:57:07Z")\
**Posts on this page:** 16\
**Page:** 1

<div class="post-metadata">

**Author:** ![Liamzy](https://avatars.discourse-cdn.com/v4/letter/l/50afbb/32.png) [@Liamzy](https://discourse.haskell.org/u/Liamzy)\
**Post date:** [August 27, 2023, 5:57am UTC](https://discourse.haskell.org/t/statet-performance-benchmarks/7439/1 "2023-08-27T05:57:07Z")

</div>

Informally, I find that accum parameter with TCO is the most performant implementation of “state”, as tested with informal naive factorial.

Hell, my benchmark even has Haskell in the region of Rust, ffs, or maybe I misconfigured my TCO benchmark (it probably has more to do with bigInt implementations, Julia actually wins here).

What are actual performance tips for accum parameter vs foldl’ vs StateT vs iterate and iterate’ vs ST / IORef?

---

<div class="post-metadata">

**Author:** ![tomjaguarpaw](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/tomjaguarpaw/32/1230_2.png) [@tomjaguarpaw](https://discourse.haskell.org/u/tomjaguarpaw)\
**Post date:** [August 27, 2023, 7:01am UTC](https://discourse.haskell.org/t/statet-performance-benchmarks/7439/2 "2023-08-27T07:01:40Z")

</div>

You might like to share the code. I for one don’t know what you mean by “accum parameter with TCO”.

---

<div class="post-metadata">

**Author:** ![ReleaseCandidate](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/releasecandidate/32/2849_2.png) [@ReleaseCandidate](https://discourse.haskell.org/u/ReleaseCandidate)\
**Post date:** [August 27, 2023, 7:11am UTC](https://discourse.haskell.org/t/statet-performance-benchmarks/7439/3 "2023-08-27T07:11:01Z")

</div>

> [@tomjaguarpaw](#):
>
> I for one don’t know what you mean by “accum parameter with TCO”.

Tail Call Optimisation, I guess.

---

<div class="post-metadata">

**Author:** ![tomjaguarpaw](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/tomjaguarpaw/32/1230_2.png) [@tomjaguarpaw](https://discourse.haskell.org/u/tomjaguarpaw)\
**Post date:** [August 27, 2023, 7:16am UTC](https://discourse.haskell.org/t/statet-performance-benchmarks/7439/4 "2023-08-27T07:16:35Z")

</div>

> [@Liamzy](#):
>
> most performant implementation of “state”,

I guess so too, but I’m not sure what that has to do with ‘the most performant implementation of “state”’.

---

<div class="post-metadata">

**Author:** ![Liamzy](https://avatars.discourse-cdn.com/v4/letter/l/50afbb/32.png) [@Liamzy](https://discourse.haskell.org/u/Liamzy)\
**Post date:** [August 27, 2023, 7:39am UTC](https://discourse.haskell.org/t/statet-performance-benchmarks/7439/5 "2023-08-27T07:39:04Z")

</div>

This is an old benchmarker:

[https://paste.tomsmeding.com/vyxd6Tdd](https://paste.tomsmeding.com/vyxd6Tdd)

* * *

TBH, one curiosity I have is whether mapAccumL is miswritten, i.e, should it be ditching its custom State type entirely and just using straight accumulating parameters (that’s what I mean by accum param)?

---

<div class="post-metadata">

**Author:** ![jaror](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/jaror/32/3271_2.png) [@jaror](https://discourse.haskell.org/u/jaror)\
**Post date:** [August 27, 2023, 12:31pm UTC](https://discourse.haskell.org/t/statet-performance-benchmarks/7439/6 "2023-08-27T12:31:51Z")

</div>

GHC should be able to optimise direct tail recursion with an accumulating parameter, `foldl'`, and `StateT` all to the same efficient code. ST / IORef always introduces a layer of indirection and thus memory access in the tight loop (like if you would mark variables as `volatile` in C) so those will be slower. I don’t know exactly how `iterate` and `iterate'` fit into this picture.

To give a concrete example, these three all produce very similar Core (although they’re all slightly different in inconsequential ways):

```haskell
facAcc :: Int -> Int
facAcc = go 1 where
  go !s 1 = s
  go !s !n = go (s * n) (n - 1)

facFold :: Int -> Int
facFold n = foldl' (*) 1 [1..n]

facState :: Int -> Int
facState n = execState (go n) 1 where
  go 1 = pure ()
  go n = do modify (* n); go (n - 1) 

```

---

<div class="post-metadata">

**Author:** ![Bodigrim](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/bodigrim/32/1457_2.png) [@Bodigrim](https://discourse.haskell.org/u/Bodigrim)\
**Post date:** [August 27, 2023, 12:39pm UTC](https://discourse.haskell.org/t/statet-performance-benchmarks/7439/7 "2023-08-27T12:39:28Z")

</div>

Seems related: [StateT vs. IORef: a benchmark](https://ro-che.info/articles/2020-12-29-statet-vs-ioref)

---

<div class="post-metadata">

**Author:** ![Liamzy](https://avatars.discourse-cdn.com/v4/letter/l/50afbb/32.png) [@Liamzy](https://discourse.haskell.org/u/Liamzy)\
**Post date:** [August 27, 2023, 1:36pm UTC](https://discourse.haskell.org/t/statet-performance-benchmarks/7439/8 "2023-08-27T13:36:11Z")

</div>

I distinctly recall that StateT was slower in my experience, but perhaps it was simply my experience or issues with Clang backend / OS / earlier version with GHC.

[https://paste.tomsmeding.com/ghkcT0Zx](https://paste.tomsmeding.com/ghkcT0Zx)

On recent benchmarks on GHC 9.6.2 on ArchLinux, I’m seeing roughly what’s been described, i.e, State etc are low or zero cost compared to accumulating parameter recursion.

* * *

The only weirdness is for\_ and foldl’; i.e, there seems to be some sort of cost incurred in generating the list (10-20%), but compared to my Windows experience, it’s significantly lower.

Shouldn’t stream fusion just be turning this into a loop anyways?

---

<div class="post-metadata">

**Author:** ![jaror](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/jaror/32/3271_2.png) [@jaror](https://discourse.haskell.org/u/jaror)\
**Post date:** [August 27, 2023, 2:15pm UTC](https://discourse.haskell.org/t/statet-performance-benchmarks/7439/9 "2023-08-27T14:15:07Z")

</div>

I think 20 is still an extremely small input. The function only takes a few hundred nanoseconds. At that scale there are a lot of confounding factors. If I run your program on an input of `10000` then I get quite consistent timings of about 5ms, although there are a few of around `10ms` which I’d ascribe to code layout.

I wish we had a benchmarking tool as described here: [https://www.youtube.com/watch?v=r-TLSBdHe1A](https://www.youtube.com/watch?v=r-TLSBdHe1A)

Edit: Actually, I think the 5ms/10ms difference might be due to strictness. With your program as written all the `facState*` benchmarks take 10ms and some become 5ms if I instead use `Control.Monad.Trans.State.Strict`.

---

<div class="post-metadata">

**Author:** ![Liamzy](https://avatars.discourse-cdn.com/v4/letter/l/50afbb/32.png) [@Liamzy](https://discourse.haskell.org/u/Liamzy)\
**Post date:** [August 27, 2023, 2:35pm UTC](https://discourse.haskell.org/t/statet-performance-benchmarks/7439/10 "2023-08-27T14:35:07Z")

</div>

Thoughts?

 ![image](https://us1.discourse-cdn.com/flex002/uploads/haskell/original/2X/d/dbf14c0b206248e955d0feb9dc6c3e8d112502cb.png)  
 ![image](https://us1.discourse-cdn.com/flex002/uploads/haskell/original/2X/5/55bdbcaa35b89bcdd93436fe8ae6b0bfd9ef64fa.png)

 ![image](https://us1.discourse-cdn.com/flex002/uploads/haskell/original/2X/d/d8a464df155746ef7b86de4aede207c03ca5974f.png)  
 ![image](https://us1.discourse-cdn.com/flex002/uploads/haskell/original/2X/d/d1c98955500825a7c5a244af63ba8a557071132b.png)

Pastebin of source:

> **[Paste: id5tlMaA](https://paste.tomsmeding.com/id5tlMaA)**

---

<div class="post-metadata">

**Author:** ![jaror](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/jaror/32/3271_2.png) [@jaror](https://discourse.haskell.org/u/jaror)\
**Post date:** [August 27, 2023, 2:43pm UTC](https://discourse.haskell.org/t/statet-performance-benchmarks/7439/11 "2023-08-27T14:43:56Z")

</div>

Yeah, that seems consistent with my results. There is indeed a difference. In the Core dump (`-ddump-simpl`) I do notice this:

```haskell
Rec {
$wloop
  = \ ds eta ->
      case ds of wild {
        IS x1 ->
          case x1 of {
            __DEFAULT -> $wloop (integerSub wild fac1) (integerMul eta wild);
            1# -> (# eta #)
          };
        IP x1 -> $wloop (integerSub wild fac1) (integerMul eta wild);
        IN x1 -> $wloop (integerSub wild fac1) (integerMul eta wild)
      }
end Rec }

facStateT' = \ n -> case $wloop n fac1 of { (# ww #) -> ww }

facStateT = facStateT'

facState' = facStateT'

facState = facStateT'

```

So all those functions are actually compiled to exactly the same thing. In the STG dump (`-ddump-stg-cg`) you can see how `$wloop` is compiled more clearly:

```haskell
Rec {
$wloop =
    \r [ds eta]
        case ds<TagProper> of wild {
          IS x1 ->
              case x1<TagProper> of {
                __DEFAULT ->
                    let { sat = \u [] integerMul eta wild;
                    } in 
                      case integerSub wild fac1 of sat { __DEFAULT -> $wloop sat sat; };
                1# -> Solo# [eta];
              };
          IP _ ->
              let { sat = \u [] integerMul eta wild;
              } in 
                case integerSub wild fac1 of sat { __DEFAULT -> $wloop sat sat; };
          IN _ ->
              let { sat = \u [] integerMul eta wild;
              } in 
                case integerSub wild fac1 of sat { __DEFAULT -> $wloop sat sat; };
        };
end Rec }

```

All those `let`s are thunk allocations. So the integer multiplications all become thunks which slows things down.

If we use `Control.Monad.Trans.State.Strict` instead we see another version of `$wloop`:

```haskell
Rec {
$wloop1 =
    \r [ds eta]
        let-no-escape {
          $j =
              \r []
                  case integerMul eta ds of vx {
                  __DEFAULT ->
                  case integerSub ds fac1 of sat { __DEFAULT -> $wloop1 sat vx; };
                  };
        } in 
          case ds<TagProper> of {
            IS x1 ->
                case x1<TagProper> of {
                  __DEFAULT -> $j<TagProper>;
                  1# -> Solo# [eta];
                };
            IP _ -> $j<TagProper>;
            IN _ -> $j<TagProper>;
          };
end Rec }

```

This one does not allocate thunks. But this one is only used by `facState'` and `facStateT'`.

In conclusion, you need to use both `modify'` and the strict `State`/`StateT` monad for the best performance in this case.

@sgraf can you tell why the demand analyser is not always good enough to figure out the strictness in these cases? Oh, it must be because that `Solo#` is lazy. If only it could use information from the use-site where the tuple is immediately unpacked:

```haskell
facStateT' = \ n -> case $wloop n fac1 of { (# ww #) -> ww }

```

---

<div class="post-metadata">

**Author:** ![sgraf](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/sgraf/32/392_2.png) [@sgraf](https://discourse.haskell.org/u/sgraf)\
**Post date:** [August 27, 2023, 3:16pm UTC](https://discourse.haskell.org/t/statet-performance-benchmarks/7439/12 "2023-08-27T15:16:53Z")

</div>

Just from skimming the code listings, you might be thinking of return-pattern specialisation as proposed in [#16335: CPR Analysis is too conservative for certain inductive cases · Issues · Glasgow Haskell Compiler / GHC · GitLab](https://gitlab.haskell.org/ghc/ghc/-/issues/16335).

Demand/CPR analysis would not be able to unbox the result because there can be call sites that would not need to evaluate the field of the Solo# constructor; and WW/DmdAnal does not duplicate code.

Edit:Although as you say, when all use sites are known to unbox and use the state, a smarter DmdAnal should be able to spot this. That’s a long term thing that I’m trying to solve.

---

<div class="post-metadata">

**Author:** ![sgraf](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/sgraf/32/392_2.png) [@sgraf](https://discourse.haskell.org/u/sgraf)\
**Post date:** [August 27, 2023, 3:17pm UTC](https://discourse.haskell.org/t/statet-performance-benchmarks/7439/13 "2023-08-27T15:17:58Z")

</div>

Try making the field of Solo# strict or use $! on the state for Nested CPR to fire

---

<div class="post-metadata">

**Author:** ![Liamzy](https://avatars.discourse-cdn.com/v4/letter/l/50afbb/32.png) [@Liamzy](https://discourse.haskell.org/u/Liamzy)\
**Post date:** [August 27, 2023, 3:32pm UTC](https://discourse.haskell.org/t/statet-performance-benchmarks/7439/14 "2023-08-27T15:32:56Z")

</div>

Just retested; it looks like I forgot to set facStateS’ to use S.modify’ and was accidentally running it on S.modify.

From benchmarks, it should be comparable to accumulator fac, fold fac, and for fac (which incidentally pulls ahead at very large numbers, despite being relatively unperformant at small numbers, and still works decently despite running on default State monad).

* * *

There was also an error in the benchmarking code regarding for, wherein the factorial wasn’t computing the correct result.

* * *

[https://paste.tomsmeding.com/7wtcxovu](https://paste.tomsmeding.com/7wtcxovu)

Source code above for benchmarks.

[https://paste.tomsmeding.com/tOLf1KNH](https://paste.tomsmeding.com/tOLf1KNH)

Final set of benchmarks.

* * *

So it does look that Control.Monad.Trans.State.Strict is approximately zero-cost, and can be used recklessly as a replacement for accumulating parameter idiom in concert with modify’. The for\_ idiom actually outperforms both folds and straight accumulating parameter for large n.

I read about Strict State Monad and modify’ on Kowainik a long time ago, iirc, but it looks like they moved to a new host and the old post is gone. But strangely enough, I didn’t get these results the last time I benchmarked naive factorial across idioms. Probably user error on my part (forgot to get Control.Monad.Trans.Strict)

* * *

Space-leaking monad transformers have been a huge gripe of mine traditionally; i.e, Haskell really emphasizes its monads and unperformant monads with huge performance penalties are somewhat embarrassing.

It’s nice to know that at least StateT.Strict is safe, but that calls to mind, why isn’t StateT.Strict the default on Control.Monad.Trans.State? You can’t really hide modify to get people to use the “correct” modify’ first, but at least pointing Control.Monad.Trans.State to StateT.Strict would make life simpler and Haskell less footgunny; same applies to the mtl library version.

---

<div class="post-metadata">

**Author:** ![jaror](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/jaror/32/3271_2.png) [@jaror](https://discourse.haskell.org/u/jaror)\
**Post date:** [August 27, 2023, 8:29pm UTC](https://discourse.haskell.org/t/statet-performance-benchmarks/7439/15 "2023-08-27T20:29:07Z")

</div>

> [@sgraf](#):
>
> Try making the field of Solo# strict or use $! on the state for Nested CPR to fire

The problem is that the `Solo#` (a.k.a. `(# _ #)`) is not in our code, It comes from the a worker wrapper transformation of the (a, s) tuple in `Control.Monad.Trans.State.Strict.StateT`. Maybe that package should use a specialised tuple data type that is strict in the state.

I guess using `modify'` works too, but I think most people would want the state to always be forced, especially if they’ve already chosen to use the `.Strict` version.

---

<div class="post-metadata">

**Author:** ![tomjaguarpaw](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/tomjaguarpaw/32/1230_2.png) [@tomjaguarpaw](https://discourse.haskell.org/u/tomjaguarpaw)\
**Post date:** [September 13, 2023, 12:45pm UTC](https://discourse.haskell.org/t/statet-performance-benchmarks/7439/16 "2023-09-13T12:45:27Z")

</div>

> [@Liamzy](#):
>
> It’s nice to know that at least StateT.Strict is safe, but that calls to mind, why isn’t StateT.Strict the default on Control.Monad.Trans.State? You can’t really hide modify to get people to use the “correct” modify’ first, but at least pointing Control.Monad.Trans.State to StateT.Strict would make life simpler and Haskell less footgunny; same applies to the mtl library version.

Agreed, but that would potentially be a silent breaking change so is rather dangerous. We should, however, try to discourage people from using the `Lazy` versions and from using `modify`.
