Skip to content

very bad performance of iterator on array of union types #40950

@lmiq

Description

@lmiq

This a simplified example of this thread on discourse, but which appears to have revealed an inefficient behaviour of one of the common iterators when dealing with arrays of mixed Union types. Here is the simplified example:

using BenchmarkTools, Test

struct A x::Float64 end
struct B x::Float64 end
struct C x::Float64 end
struct D x::Float64 end
struct E x::Float64 end

function sum1(v)
  s = 0.
  for x in v
    s += x.x
  end
  s
end

function sum2(v)
  s = 0.
  for (i,x) in pairs(v)
    s += x.x
  end
  s
end

t = [A,B,C,D,E]
v = Union{A,B,C,D,E}[rand(t)(rand()) for i in 1:1000]

@test sum1(v) ≈ sum2(v)

@btime sum1($v)

@btime sum2($v)

result (Julia 1.6.1):

  241.063 μs (7980 allocations: 140.31 KiB)
  992.583 ns (0 allocations: 0 bytes)
501.12183238665824

Thus, iterating with for x in v is much worse than using for (i,x) in pairs(v), which does not appear to make any sense in terms of functionality.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions