# Fastest way to permute Array, given some permutation

**URL:** https://discourse.julialang.org/t/fastest-way-to-permute-array-given-some-permutation/49687
**Category:** Performance
**Tags:** sortperm, arrays
**Created:** [November 6, 2020, 3:42pm UTC](https://discourse.julialang.org/t/fastest-way-to-permute-array-given-some-permutation/49687 "2020-11-06T15:42:14Z")
**Posts on this page:** 1
**Showing post:** 6

<div class="post-metadata">

### Author: ![Henrique\_Becker](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/henrique_becker/32/15443_2.png) [@Henrique\_Becker](https://discourse.julialang.org/u/Henrique_Becker)
#### Post date: [November 8, 2020, 9:59pm UTC](https://discourse.julialang.org/t/fastest-way-to-permute-array-given-some-permutation/49687/6 "2020-11-08T21:59:51Z")

</div>

Note that over-optimizing permutations may cause damage to your sanity, I know because I had to do it for maximum efficiency to replicate a literature heuristic.

The optimized heuristic code is [here](https://github.com/henriquebecker91/GuillotineModels.jl/blob/master/src/ppg2kp/Heuristic.jl#L280--L373). Basically, for each `Vector` that needs to be permuted frequently, I allocate a copy a single time, and then in the literal million iterations following, I copy-permute the original vector to the copy, and then swap who is the copy and who is the original in the loop scope.

I also had to gut the `sort` internals, it was not pretty. But I got rid of any allocations and my final code was six times faster. I just had to keep the old code to be able to check if the results were the same, or I introduced any bugs.

---

_[View the full topic](https://discourse.julialang.org/t/fastest-way-to-permute-array-given-some-permutation/49687)._
