Skip to main content

compile - Why Function is not identical to `&` in autocompilation?


Here is the example, copied from here



square = Function[x, x^2];
square1 = #^2 &;

the timing and unpacking status shows


data = RandomReal[{0, 10}, {10000}];

AbsoluteTiming[Developer`PackedArrayQ[Map[square, data]]]
AbsoluteTiming[Developer`PackedArrayQ[tmp1 = Map[square1, data]]]

{0.000771589, True}

{0.000748647, True}

Now we add external variable into these two definition.


a = 1
square = Function[x, x^2 + a];
square1 = #^2 + a &;

and time it again, you got


{0.0336384, False}
{0.0062035, True}


we can see & is still autocompiled, while Function is not. Why? I think the documentation treats them as identical way of writing. This distinction is oddly subtle, I just found it today. What is bad is that without Function, we can not give parameters names, thus less readability.




Comments