function with_ternary() sum(x%3==0 || x%5==0 ? x : 0 for x=1:999999999) end function with_if() sum(x for x=1:999999999 if x%3 == 0 || x%5 == 0) end
I call @time with_if() and @time with_ternary() several times after that to make sure it’s already compiled. The results show me that with_ternary() funcition is 2 times faster than with_if() function. Can someone explain to why is that the case?
I know that two functions are not exactly the same because with_ternary() is passing zeros to the sum() function. So why is it so much faster?
@time with_ternary() 233333333166666668 2.206624 seconds (7 allocations: 240 bytes)
@time with_if() 233333333166666668 4.835853 seconds (12 allocations: 416 bytes)