# The quasi-best MaxN function

**URL:** https://discourse.julialang.org/t/the-quasi-best-maxn-function/52813
**Category:** Performance
**Created:** [January 4, 2021, 9:32am UTC](https://discourse.julialang.org/t/the-quasi-best-maxn-function/52813 "2021-01-04T09:32:15Z")
**Posts on this page:** 1
**Showing post:** 12

<div class="post-metadata">

### Author: ![mikkoku](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mikkoku/32/16274_2.png) [@mikkoku](https://discourse.julialang.org/u/mikkoku)
#### Post date: [January 6, 2021, 3:53pm UTC](https://discourse.julialang.org/t/the-quasi-best-maxn-function/52813/12 "2021-01-06T15:53:01Z")

</div>

You can still squeeze a little bit by removing the array access `maxn[N]` in the loop.

```julia
function MaxN6c2(cr,N)
    maxn = sort!(cr[1:N], rev=true)
    maxnN = maxn[N]
    @inbounds for i in N+1:length(cr)
        e=cr[i]
        if maxnN < e
            insert1(maxn,N,e)
            maxnN = maxn[N]
        end
    end
    maxn
end

```

```julia
julia> @btime MaxN6c2($re6, 20);
  555.000 μs (203 allocations: 32.78 KiB)
julia> @btime MaxN6c1($re6, 20);
  735.699 μs (203 allocations: 32.78 KiB)
julia> @btime nlargest(20, $re6);
  858.300 μs (2 allocations: 480 bytes)

```

(This would probably apply to nlargest as well.)

---

_[View the full topic](https://discourse.julialang.org/t/the-quasi-best-maxn-function/52813)._
