Skip to content

Instantly share code, notes, and snippets.

@Datseris
Created March 29, 2018 18:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Datseris/98b689c2b4dc37516c5051efc6e6a7a4 to your computer and use it in GitHub Desktop.
Save Datseris/98b689c2b4dc37516c5051efc6e6a7a4 to your computer and use it in GitHub Desktop.
function f1(N::Int)
s = 0
for n = 1:N
n % 2 == 0 && (s += 2; continue)
s += 1
end
s
end
function f2(N::Int)
s = 0
for n = 1:N
s += ifelse(n%2==0, 2, 1)
end
s
end
function f3(N::Int)
s = 0
for n = 1:N
s += n%2 == 0 ? 2 : 1
end
s
end
function f33(N::Int)
s = 0
for n = 1:N
n%2 == 0 ? s += 2 : s += 1
end
s
end
function f4(N::Int)
s = 0
for n = 1:N
if n%2 == 0
s+=2
else
s+=1
end
end
s
end
using BenchmarkTools
pass = true
K = 0
for K in [99, 100, 100000]
print(" short circuit ($K): ")
a1= @btime f1($K)
print(" ifelse ($K): ")
a2= @btime f2($K)
print(" tertiary op ? ($K): ")
a3= @btime f3($K)
print(" alternative ? ($K): ")
a33= @btime f33($K)
print(" branching ($K): ")
a4= @btime f4($K)
println()
pass = pass && (a1==a2==a3==a33==a4)
end
pass && println("same results")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment