F#: removing duplicates from a seq is slow

后端 未结 9 1081
半阙折子戏
半阙折子戏 2021-01-12 03:11

I am attempting to write a function that weeds out consecutive duplicates, as determined by a given equality function, from a seq<\'a> but with a twist:

9条回答
  •  北荒
    北荒 (楼主)
    2021-01-12 04:05

    Seq.isEmpty, Seq.head and Seq.tail are slow because they all create a new Enumerator instance which it then calls into. You end up with a lot of GC.

    Generally, Sequences are forward only, and if you use them 'like pattern matching for lists', the performance becomes really shoddy.

    Looking a bit at your code... | None -> yield! s creates a new Enumerator even though we know s is empty. Every recursive call probably ends up creating a new IEnumerable that is then directly turned into an Enumerator from the call-site with yield!.

提交回复
热议问题