Mathematica Stack Exchange is a question and answer site for users of Mathematica. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

When is there an advantage to using Block in Compile? For instance, if I have a multiple-step code, how do I decide which variable assignments I should put into the first argument of Block[]? Is it unwise to have functions being evaluated in there?

share|improve this question
See here for some germane details in Leonid's answer. – ciao May 30 '14 at 9:15
up vote 7 down vote accepted

Block (or Module) is used for creating local variables in Compile. (When used with Compile they're equivalent.) You need to use them whenever you need to use any variables in compiled code.


The following code does not localize y:

cf = Compile[{x},
  y = x*x;

Since y is not localized to the body of Compile, it is treated as a global variable, and will trigger calling back to the main evaluator. The practical consequence of this is that the program will run very slowly: the evaluation of y, or any assignments to y, will not be compiled. The function will still work, but it will not be fast because only certain parts will be compiled.

CompilePrint gives

1   V17 = MainEvaluate[ Function[{x}, y = x x][ R0]]
2   R1 = MainEvaluate[ Function[{x}, y][ R0]]
3   R2 = MainEvaluate[ Function[{x}, y][ R0]]
4   R1 = R1 * R2
5   Return

The correct way to write this is

cf = Compile[{x},
   y = x*x;

Now y is localized and the function can be fully compiled, so it will run much faster.

1   R1 = R0 * R0
2   R2 = R1 * R1
3   Return

Note: It does not matter whether you use

Block[{var = 1},


  var = 1;

They have the same effect.

share|improve this answer
Thanks, I learned something new! How about function evaluation within the first argument of Block? Does it ever make sense to compile Block[{a=SomeFunction[b],c=1},...] with respect to Block[{c=1},a=Somefunction[b];...]? – Ziofil May 30 '14 at 23:18
@Ziofil It doesn't matter whether you have SomeFunction[...] or ` number there. In your second example a is not localized, which will cause the performance problem I mentioned. – Szabolcs May 31 '14 at 2:12

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.