Just to illustrate what the comments are getting at, consider these variations below. First, the three If
calculations are consistently faster than the corresponding operator versions.
Second, the time it takes to execute Print
is highly variable (see below). Finally, let me add that operators are limited in their possible values (for example, Or
yields True
or the last value).
All of these variations calculate the same list of True
or Null
values.
list = RandomInteger[{1, 10}, 10^6];
iflist = Table[
If[list[[i]] == 4, True,], {i, Length@list}]; // AbsoluteTiming
{0.889342, Null}
iflist2 = Table[If[i == 4, True,], {i, list}]; // AbsoluteTiming
{0.567959, Null}
iflist3 = If[# == 4, True,] & /@ list; // AbsoluteTiming
{0.863577, Null}
oplist = Table[(list[[i]] == 4 || Null), {i,
Length@list}]; // AbsoluteTiming
{0.963072, Null}
oplist2 = Table[(i == 4 || Null), {i, list}]; // AbsoluteTiming
{0.627932, Null}
oplist3 = # == 4 || Null & /@ list; // AbsoluteTiming
{0.950945, Null}
Note the form Table[.., {i, list}]
is fastest in both cases, showing that the speed of If
versus operator is not the major factor here either.
Here are the results of a few runs of the original code with Print
.
There is difference between the two calculations: the first makes a list of all Null
, while in the second all but the last element is True
. I tested a variation in which they calculate the same result, but clearly that difference is unimportant.
oldlist = Range[4000];
Table[If[oldlist[[i]] == 4000, Print[1], Print[2]], {i, 4000}]; // AbsoluteTiming
{23.495759, Null}
{68.451701, Null}
{22.523382, Null}
Table[(oldlist[[i]] == 4000 && (Print[1]; True) || Print[2]), {i, 4000}]; // AbsoluteTiming
{8.112765, Null}
{17.992601, Null}
{81.830045, Null}
Compare with a version that calculates the same list as the previous example:
Table[If[oldlist[[i]] == 4000, Print[1]; True, Print[2]], {i,
4000}]; // AbsoluteTiming
{9.473233, Null}
{46.342906, Null}
{21.116975, Null}