Skip to content

Use ternary operator instead of ifelse #26

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 6, 2021
Merged

Use ternary operator instead of ifelse #26

merged 1 commit into from
Sep 6, 2021

Conversation

devmotion
Copy link
Member

In benchmarks of JuliaStats/StatsBase.jl#714 and the examples shown below it seems that on my computer the ternary operator is sometimes faster than ifelse (which evaluates all branches) and never slower:

With the latest release:

julia> using LogExpFunctions, BenchmarkTools, Random

julia> Random.seed!(1234);

julia> out = Vector{Float64}(undef,100_000);

julia> x, y = rand(100_000), rand(100_000);

julia> @btime map!(xlogx, $out, $x);
  717.358 μs (0 allocations: 0 bytes)

julia> @btime map!(xlogy, $out, $x, $y);
  780.322 μs (0 allocations: 0 bytes)

julia> @btime map!(logistic, $out, $x);
  745.426 μs (0 allocations: 0 bytes)

julia> @btime map!(logaddexp, $out, $x, $y);
  2.502 ms (0 allocations: 0 bytes)

julia> @btime sum(xlogx, $x); # similar to https://github.com/JuliaStats/StatsBase.jl/pull/714
  780.203 μs (0 allocations: 0 bytes)

With this PR:

julia> using LogExpFunctions, BenchmarkTools, Random

julia> Random.seed!(1234);

julia> out = Vector{Float64}(undef,100_000);

julia> x, y = rand(100_000), rand(100_000);

julia> @btime map!(xlogx, $out, $x);
  703.294 μs (0 allocations: 0 bytes)

julia> @btime map!(xlogy, $out, $x, $y);
  780.819 μs (0 allocations: 0 bytes)

julia> @btime map!(logistic, $out, $x);
  717.576 μs (0 allocations: 0 bytes)

julia> @btime map!(logaddexp, $out, $x, $y);
  2.507 ms (0 allocations: 0 bytes)

julia> @btime sum(xlogx, $x);
  762.913 μs (0 allocations: 0 bytes)

Copy link
Member

@nalimilan nalimilan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks! AFAIK with ? LLVM will decide whether to evaluate all branches or not, while with ifelse it will always evaluate. So if we trust LLVM ? is generally better.

@devmotion devmotion merged commit be0bae2 into master Sep 6, 2021
@nalimilan nalimilan deleted the dw/ternary branch September 6, 2021 13:23
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants