Different return types in map vs comprehension for empty vectors

julia> map(Base.OneTo, Int[])
Any[]

julia> [Base.OneTo(x) for x in Int[]]
Base.OneTo{Int64}[]

julia> VERSION
v"1.9.0-beta4"

Why this difference?

1 Like

Even more interestingly,

julia> map(Base.OneTo, Int[])
Any[]

julia> map(x -> Base.OneTo(x), Int[])
Base.OneTo{Int64}[]

I think this is related to type vs function argument. Functions enjoy more specialization for some reason, leading to unexpected slowdowns or type widening.
Recently, I reported on slack what I think is related here — sort-by-Date is orders of magnitude slower than sort-by-lambda:

julia> using Dates, BenchmarkTools

julia> x = [DateTime(i) for i in 1:10000];

# baseline: plain sort
julia> @btime sort($x);
  77.782 μs (4 allocations: 117.36 KiB)

# sort by=Date is 150x slower
julia> @btime sort($x, by=Date);
  11.817 ms (218564 allocations: 3.45 MiB)

# anonymous function brings the time down, becomes just 3x slower than plain sort
julia> @btime sort($x, by=y -> Date(y));
  238.308 μs (4 allocations: 117.36 KiB)

Have absolutely no idea why this is the case.

2 Likes

There’s an issue about this: Return typing of a function is ignored when calling the `map()` function on empty objects. · Issue #46958 · JuliaLang/julia · GitHub

1 Like