Sort Perl array in place

后端 未结 3 824
生来不讨喜
生来不讨喜 2020-12-06 00:03

I have a reference to an array (called $intervals) and I would like to sort the values in this array. It\'s possible that there could be a huge number of values

3条回答
  •  -上瘾入骨i
    2020-12-06 01:01

    Since Perl 5.8.4, the in-place sort @a = sort @a is optimized. See the links below for details:

    Performance Enhancements in perl584delta

    http://perl5.git.perl.org/perl.git/commit/fe1bc4cf71e7b04d33e679798964a090d9fa7b46?f=pp_sort.c

    +    /* The optimiser converts "@a = sort @a" to "sort \@a";
    +     * in case of a tied @a, pessimise: push (@a) onto stack, then assign
    +     * the result back to @a at the end of this function */
    

    So you should be able to write:

    @$intervals = sort by_position @$intervals
    

    And in Perl's later than 5.8.3 you will see reduced memory usage (and preservation of aliasing for the rare times it matters).

提交回复
热议问题