Skip to content

Unexpected iteration performance drop when recursive loops are used. #57

@pragmatrix

Description

@pragmatrix

Description

The problem appears when a recursive asyncSeq loop yields a number of elements and at least one async bind is inside the loop.

Repro steps

The performance drop can reproduced by the following test case:

open System.Diagnostics
open FSharp.Control

let rec generate cnt = asyncSeq {
    if cnt = 0 then () else
    let! v = async.Return 1
    yield v
    yield! generate (cnt-1)
}

[1000;2000;4000]
|> List.iter (fun numbers ->
    let sw = Stopwatch.StartNew()
    generate numbers
    |> AsyncSeq.iter ignore
    |> Async.RunSynchronously
    printfn "%d: %A" numbers sw.Elapsed)

The function generate above yields cnt numberd (all '1's), and it produces the following output on my machine:

1000: 00:00:01.1934439
2000: 00:00:04.7116588
4000: 00:00:18.9604031

Expected behavior

The time it takes to iterate the asynchronous sequence should be proportional to the number of elements it generates.

Actual behavior

The performance seems to be about O(n^2) instead of O(n).

Known workarounds

Try to avoid recursion in all asyncSeq scenarios that may return more than a few hundred values.

Related information

I've tested Release builds of master and @eulerfx's perf branch with no noticable difference. A number of functions in AsyncSeq.fs use a similar looping pattern and might be affected, too.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions