Suppose that we
Ass = AssociationThread[Range[1000000], Range[1000000]^2]; // Timing
KeySelect[Ass, PrimeQ]; // Timing
Tra = Transpose[{Range[1000000], Range[1000000]^2}]; // Timing
Select[Tra, PrimeQ[#[[1]]] &]; // Timing
Here We create a list of mathematical pairs, and extract elements that meet a certain criteria. The criteria only concerns its 1st component. (1st component should be a prime number).
There are 2 method : Association
vs list of pairs
It is much faster to create such list by list of pairs
method.
Association
took 0.375 seconds, whereas Tra
took 0. seconds.
Interestingly, once such list(or association) is made, selection-job is faster in Association
.
Keyselect
took 0.484 seconds, whereas Select
took 0.922 seconds.
Not so important, but to sum up,
0.375 + 0.484 < 0.+0.922
so Association
method won in this case.
Now what you think right now and my question might be the same :
I want to create such list of pairs(equivalent) in no seconds (0. seconds like Tra
method), simultaneously,
I want to select elements by a criteria(that only concerns 1st component) as fast as Keyselect
. I want to combine the advantages of both.
And in fact I've never used Association
before. In the past, list of pairs
was sufficient tool for me. But now there is a new aspects of Association
- the performance.
Do you agree that when there are some filtering jobs(with criteria only concerns 1st component or only 2nd component)to do, it is recommended to create Association rather then list of pairs ?
To recap,
Q1) Can we construct list of mathematical pairs (anything equivalent)
with good performance of both creation and selection ?
Q2) If there are many selection jobs for a fixed structure of matheatica pairs, is it good to start with association rather then list of pairs?
RepeatedTiming
and the answers were quite different (1.74
seconds forAssociation
and1.03
for pairs withPick
).Pick[Tra, PrimeQ@Tra[[All, 1]]]
$\endgroup$