Okay, I’m dumb — the DataStructures.jl package already contains such a function, implemented using heaps.
Just call nlargest(n, array)
from DataStructures.jl — it seems to be faster than all of the implementations above, including mine, in all the cases above.
(It beats my code apparently because it takes advantage of the lower-level heap function DataStructures.percolate_down!
… nlargest
currently only supports arrays, not arbitrary iterators, but that limitation looks easy to fix if desired.)