in reply to Re^8: Better mousetrap (getting top N values from list X)
in thread Better mousetrap (getting top N values from list X)
Out of curiousity, was your comparator of the {$a <=> $b} type, or did you pass parameters to it?
I haven't worked out how to set $a and $b yet. This was the C wrapper function I used for calling the comparator.
int callComp( SV* cmp, int a, int b ) { int count, rv; dSP; ENTER; SAVETMPS; PUSHMARK(SP); XPUSHs( sv_2mortal( newSViv( a ) ) ); XPUSHs( sv_2mortal( newSViv( b ) ) ); PUTBACK; if( ( count = call_sv( cmp, G_SCALAR ) ) != 1 ) croak( "Bad comparator" ); SPAGAIN; rv = POPi; FREETMPS; LEAVE; }
That said, I am not sure how much difference it would make to the performance? You get the best performance from sort when you don't actually do anything in the comparator sub, which allows perl to completely skip the setting of parameters and the callback to perl.
But I think that the decision that allows perl to do that is embedded deep within the parser, a very specific special case, not something that could easily be transferred to extensions. I don't think it uses the hints mechanism?
That's what I suggested that when the programmer codes @s = sort{$a<=>$b} @u;, the interpreter effectively reads that as @s = sortNumericAscending @u; and sort{$bcmp$a} is effectively translated to 'sortAlphaDescending'.
Indeed, in the latest versions, @s = reverse sort @u; is also interpreted as 'sortAlphaDescending', but I don't think there is any easy way to apply that type of reinterpretation to extensions.
Actually, I think that 4 named variants would be cleaner both from the point of view of understandability: topN() or Ngreatest() doesn't make a great deal of sense in the case of wanting the N lowest values; and efficiency: avoiding the conditional code to decide which way we are ordering.
To fit in with the existing naming conventions of List::Util, they should probably be called: maxN(), minN(), maxNstr() & minNstr(). I don't really like the "defaulting" of min() and max() to numeric--which is the opposite to sort--or the "ommision" of 'num' from the names, but that's what now exists, and consistancy would be a good thing.
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^10: Better mousetrap (getting top N values from list X)
by tall_man (Parson) on Feb 04, 2005 at 22:36 UTC | |
by BrowserUk (Patriarch) on Feb 05, 2005 at 12:35 UTC | |
by BrowserUk (Patriarch) on Feb 05, 2005 at 00:18 UTC |