Mathematica Asked on June 9, 2021
I’m on Windows 10 Mathematica 12.1.1.
I would expect allocating a big ConstantArray
and comparing would be slower but apparently it is not:
RepeatedTiming[RandomReal[1, 10000] == ConstantArray[0, 10000]]
(* {0.0000589, False} *)
RepeatedTiming[ContainsOnly[RandomReal[1, 10000], {0}]]
(* {0.00309, False} *)
This becomes even worse if I add SameTest->Equal
which the documentation states allows some numerical tolerance:
RepeatedTiming[ContainsOnly[RandomReal[1, 10000], {0}, SameTest -> Equal]]
(* {7.92, False} *)
Why is the above more than ~100,000 times slower than the code that allocates a ConstantArray
with a large ByteCount
?! What is going on behind the scenes in ContainsOnly
that’s more expensive than allocation?
Admittedly, in this much bigger case involving sparse arrays ContainsOnly
is faster, so I’d guess the allocation overhead eventually catches up:
RepeatedTiming[SparseArray[999999 -> 1] == ConstantArray[0, 1000000]]
(* {0.00212, False} *)
RepeatedTiming[ContainsOnly[SparseArray[999999 -> 1, 1000000], {0}]]
(* {0.0000169, False} *)
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP