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.
Examine what is said, not who speaks.
Silence betokens consent.
Love the truth but pardon error.
|