You can also write [ x for x in [1,2,3] if x in [3,4,5]]
, and I am mentioning this because it is, at least in this simple test, faster than intersect
:
julia> using BenchmarkTools
julia> @btime [ i for i in [1,2,3] if i in [3,4,5] ]
173.147 ns (7 allocations: 656 bytes)
1-element Array{Int64,1}:
3
julia> @btime intersect([1,2,3],[3,4,5])
494.927 ns (15 allocations: 1.33 KiB)
1-element Array{Int64,1}:
3
EDIT: the results are not identical if there are repeated values in the vectors. In that case, you need to check what you want:
julia> @btime intersect([1, 4, 4, 5, 6], [4, 6, 6, 7, 8])
541.625 ns (14 allocations: 1.36 KiB)
2-element Array{Int64,1}:
4
6
julia> @btime [ x for x in [1, 4, 4, 5, 6] if x in [4, 6, 6, 7, 8]]
233.356 ns (9 allocations: 976 bytes)
3-element Array{Int64,1}:
4
4
6
EDIT2: Dropping repeated elements with unique!
is still faster than intersect
:
julia> v1 = rand(1:10,10);
julia> v2 = rand(1:10,20);
julia> @btime intersect($v1,$v2)
773.919 ns (15 allocations: 1.46 KiB)
6-element Array{Int64,1}:
9
7
2
3
4
1
julia> @btime unique!([ x for x in $v1 if x in $v2 ])
459.558 ns (9 allocations: 912 bytes)
6-element Array{Int64,1}:
9
7
2
3
4
1