Do you see anything wrong with this usage that would prevent the in-place optimisation from kicking in?
Yes, you are allocating the values in @a as numbers, but as you compare then as strings they are converted to strings inside the sort and perl caches the string representation.
A little program to show the effect:
Under my particular OS/perl combination, stringifying a floating point number, increases its memory usage from 32 to 96 bytes.use Devel::Peek; my @a = (1.1, 2.2); print STDERR "allocated as:\n"; Dump \@a; @a = sort { $a <=> $b } @a; print STDERR "\nsorted as numbers:\n"; Dump \@a; @a = sort @a; print STDERR "\nsorted as strings:\n"; Dump \@a;
A simple (an slow) workaround is to use two auxiliary variables for the comparison:
@a = sort { my ($b, $c) = ($a, $b); $b cmp $c } @a
In reply to Re^7: In-place sort with order assignment
by salva
in thread In-place sort with order assignment
by BrowserUk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |