Consider the following example, which generate two identical arrays. Why sometimes the array is packed and sometimes it doesn't? And why they perform differently?
Here the arrays are packed:
ht = 0.002; Ti = 0.4;
a1 = Table[Sin[x], {x, 0.2, 50., 0.02}]; // AbsoluteTiming
a2 = Table[Sin[x], {x, 0.5 Ti, 125 Ti, 0.05 Ti}]; // AbsoluteTiming
Developer`PackedArrayQ[a1]
Developer`PackedArrayQ[a2]
a1 == a2
(*
{0.010927, Null}
{0.335707, Null}
True
True
True
*)
Here one array is packed and the other is not:
a1 = Table[Sin[x], {x, 0.2, 50., 0.2}, {t, 0.002, 25., 0.002}]; // AbsoluteTiming
a2 = Table[Sin[x], {x, 0.5 Ti, 125 Ti, 0.5 Ti}, {t, ht, 12500 ht, ht}]; // AbsoluteTiming
Developer`PackedArrayQ[a1]
Developer`PackedArrayQ[a2]
a1 == a2
(*
{0.371184, Null}
{1.610365, Null}
True
False
True
*)
Since they have huge difference in performance, does that mean we should avoid using variables , instead we should use numbers in the code? Or add Evaluate
everywhere we have variables?
Table
can't check that the array will be rectangular, for symbolic array bounds, and so does not pack / auto-compile in this case. $\endgroup$