How to avoid for blocks to evaluate

I learned some blocks like if or begin or short-circuit evaluate last expression and they also have values(I don’t know concise words.)

1 + if true

this results 21.

false || 1+begin

this results 21.

Does this behavior cost additional memories? if it is, how can I avoid the behavior when I prefer that?

It is unclear what you mean here, but it is probably not correct. Where did you encounter this?

if and begin don’t short-circuit anything, but it is correct that their value is the value of the last contained expression.

The compiler may optimize out certain expressions if it can prove that this does not change anything. Eg in

julia> function donothing(x)
       y = x^2 + 9*x - 1
donothing (generic function with 1 method)


julia> @code_llvm donothing(1)

;  @ REPL[4]:2 within `donothing'
define i64 @julia_donothing_16331(i64) {
;  @ REPL[4]:3 within `donothing'
  ret i64 %0

They cost nothing when the result is not used, at least in local scope.
They of course cost something when you run them in the repl, I.e. the printing in the repl is not free, but that can be suppressed with ; as usual.


Thanks for advice but I can’t read @code_llvm informations yet. Could you give me a help?

Please don’t suggest that when it’s unnecessary, if anything the typed and optimized Julia ir should be enough to show the optimization.

Note that the dead code elimination isn’t even relevant here. In both cases the op are comparing, the results are unused. (Either the result of the last expression being unused by the enclosing block or the result of the block, I.e. the result of the last expression being unused by the “caller”).

If you want to understand llvm IR (which is really unnecessary for almost all users) you can check LLVM Language Reference Manual — LLVM 16.0.0git documentation.

1 Like