Wolfram Language Speed Guide

By Xah Lee. Date: . Last updated: .

Apply Plus vs Total vs Norm

Equivalent way to define a function. This computes geometric inversion.

f1[p_] := p/(Plus @@ (p^2));
f2 = #/(Plus@@(#^2))&;
f3 = #/Norm[#]^2 &;
f4 = #/Total[#^2] &;

vecLength = 3;
count = 100000;
testData = Table[ RandomReal[], {count},{vecLength}];

result = (( (Timing[# /@ testData]) &) /@ {f1,f2,f3,f4})

Equal@@ (((#[[2]]) &)/@ result) //Print
(* True *)

MapIndexed[ (({First@#, #2}) &), result ] //Print
(* {{0.34375, {1}}, {0.03125, {2}}, {0.03125, {3}}, {0.03125, {4}}} *)

Conclusion:

WolframLang Table vs Array

n=100;

result1= Timing@ Table[Cube[{x,y,z},1],{x,-n,n},{y,-n,n},{z,-n,n}];
result2= Timing@ Array[Cube[{##},1]&,{2 n+1,2 n+1,2 n+1},{-n,-n,-n}];
result3= Timing@ Array[Cube[{#1,#2,#3},1]&,{2 n+1,2 n+1,2 n+1},{-n,-n,-n}];

MapIndexed[ (({First@#, #2}) &), {result1, result2, result3} ] //Print
(* {{2.4375, {1}}, {3.765625, {2}}, {2.96875, {3}}} *)

Equal@@(((#[[2]]) &) /@ {result1, result2, result3}) //Print
(* True *)

Conclusion:

Total[v^2] vs v.v

data = Table[RandomReal[{-10, 10}], {4000000},{3}];

f1 = Total[#^2] &;
f2 = # . # &;

result= ((Timing[# /@data]) &) /@ {f1,f2};

Equal@@ (((#[[2]]) &) /@ result) //Print
(* True *)

MapIndexed[(({#[[1]],#2}) &),result] //Print
(* {{0.421875, {1}}, {0.40625, {2}}} *)

Conclusion:

v.v is faster than Total[v^2] , barely perceivable. At least if the vector components are real numbers.

optimize repeated expression?

testData = Table[RandomReal[{-10, 10}], {4 * 10^6 },{7}];

f1 = With[{x = # . # }, If[ x < 0.001 , #, #/x] ] &;
f2 = If[ (# . #) < 0.001 , #, #/(# . #)] &;

Timing[result1 = f1 /@ testData]//First //Print
(* 1.265625 *)

Timing[result2 = f2 /@ testData]//First //Print
(* 1.671875 *)

result1 == result2 //Print

(* True *)

Conclusion:

if you have a repeated expr, better use a temp constant for the expr.

WolframLang Tutorial