Which of the following 2 methods is better for heavy serial calculations?
Method 1:
f[x_Integer]:=Module[{...}, ...]
f[x_Real]:=Module[{...}, ...]
Method 2:
f[x_]:=Module[{...}, ...
If[Head[x]===Integer
, ...
, ...
]
]
Mathematica Stack Exchange is a question and answer site for users of Wolfram Mathematica. It only takes a minute to sign up.
Sign up to join this communityDoes this help?:
f1[x_Integer] := x^3;
f1[x_Real] := x^3;
f2[x_] := If[Head[x] === Integer, x^3, x^3];
f3[x_] := If[MatchQ[x, _Integer], x^3, x^3];
input = {RandomInteger[10, 10^5], RandomReal[1, 10^5]};
Map[f1, input, {2}]; // AbsoluteTiming
Map[f2, input, {2}]; // AbsoluteTiming
Map[f3, input, {2}]; // AbsoluteTiming
(*
{0.165381, Null}
{0.327146, Null}
{0.306359, Null}
*)
If you plan to map your function over PackedArray
s and if the body is vectorized then it might be better to perform only one check in the beginning at let loose the vectorization:
f1[x_Integer] := x^3;
f1[x_Real] := x^2;
PackedIntegerArrayQ[x_] := Developer`PackedArrayQ[x, Integer];
PackedRealArrayQ[x_] := Developer`PackedArrayQ[x, Real];
f4[x_?PackedIntegerArrayQ] := x^3;
f4[x_?PackedRealArrayQ] := x^2;
Now the test:
input = {RandomInteger[10, 10^5], RandomReal[1, 10^5]};
output1 = Map[f1, input, {2}]; // AbsoluteTiming // First
output2 = f4 /@ input; // AbsoluteTiming // First
output1 == output2
0.138853
0.000536
True
Developer`PackedArrayQ[a, type]
instead of your functions; see ?Developer`PackedArrayQ
. (At least in V11.2, it has a usage message.)
$\endgroup$
Feb 7, 2018 at 15:15