# Performance of different Count patterns

The two pieces of code below are functionally equivalent, and I would have expected similar performance. (The only difference between the two is the form of the pattern used.) But the second piece of code takes substantially longer. Why? (I've done this several times; the spread is never less than about 6 seconds, and usually closer to 10, on approximately a 70 second runtime).

Timing[For[i = 1, i < 1000, i++,
x = RandomReal[{0, 100}, 100000];
Count[x, r_ /; r >= 50]
];
]

(* {68.6056, Null}} *)

Timing[For[i = 1, i < 1000, i++,
x = RandomReal[{0, 100}, 100000];
Count[x, _?(# >= 50 &)]
];
]

(* {79.1529, Null} *)

• I'm not sure that there is a good reason why it has to be like this. It just happens to be like this in Mathematica 10.3. Both constructs involve evaluating some Mathematica code for each element of x, and theoretically both could be optimized in various ways ... The code that is being evaluated is clearly different, so it's not that surprising that there is a slight performance difference. – Szabolcs Nov 17 '15 at 16:05
• However, if you want much better performance, use Total@UnitStep[x - 50]. This is of course not nearly as readable as Count, and it gets even messier if you change that >= to a >. To make it easier to use these constructs I wrote the BoolEval package, using which you can do Total@BoolEval[x >= 50]. Also consider using RepeatedTiming and really really avoid For ... if you need a procedural loop, use Do. – Szabolcs Nov 17 '15 at 16:07
• @Szabolcs Thanks for the tips about UnitStep and RepeatedTiming. (And, I never use For, just for this example). – rogerl Nov 17 '15 at 21:13
• @Xavier. You are exactly correct. I retract my comment: I clearly had all kinds of syntax errors. If you define f correctly, it doesn't result in a speed-up. – march Nov 18 '15 at 0:48
• @Szabolcs However, I do take some issue with your term "slight performance difference". 11 seconds out of 68 is hardly slight... – rogerl Nov 18 '15 at 1:48