# Usage of Block in Compile

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?

-
See here for some germane details in Leonid's answer. – ciao May 30 '14 at 9:15

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.

### Example

The following code does not localize y:

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


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.

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},
Block[{y},
y = x*x;
y*y
]
]


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},
...
]


or

Block[{var},
var = 1;
...
]


They have the same effect.

-
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