Alan M. Carroll <> wrote:
> Apparently I wrote it badly, but my question concerning scalar vs.
> $#array was whether there was a difference in run-time costs, not the
> functional difference.  
> 
> I don't have a specific issue, but code can always run faster. The
> question is whether I should use scalar() without concern, or whether
> I should try to cache the result. For instance, if scalar is O(n),
> then this loop:   
> 
> for ( my $i = 0 ; i < scalar(@objs) ; ++i ) { ... }
> 
> becomes O(n^2) instead of O(n). That's exactly the kind of thing that
> adds up without raising an obvious red flag in profiling. 
> 
> One could then make it O(n) by doing
> 
> my $limit = scalar(@objs);
> for ( my $i = 0 ; $i < $limit; ++$i ) { ... }
> 
> If $# is O(1) instead of O(n) then it would be good to have the habit
> of using 
> 
> for (my $i = 0 ; $i <= $#objs ; ++$i) { ... }
> 
> Or, if one is building a list and needs to check later if the list is
> non-empty, should one set a flag during the list build or just use
> scalar() at the end?  
> 
> The question is, should I try to make a habit of one of these in
> particular? Or does it matter? 

The habit to get into is writing well designed easy to understand code.
Leave optimisation until it is actually necessary. Don't forget, the
first rule of optimisation is "Don't do it yet", also, I think it was
Knuth who said "Premature optimisation is the root of all evil".

I don't think it matters very much which idiom you use, although I
rarely use the C style for loop. I tend to use either "foreach my $obj
(@objs) {...}", or "for my $i (0..$#objs) {...}" if the indices are
needed, both of which are generally considered more "perl-ish". Not to
mention making your question of whether scalar(@objs) or $#objs is
faster kind of redundant.

> 
> For question (2), I tried option (C) but its failure was masked by
> other problems. Once I had those fixed, I realized that it didn't
> work.  I thought about changing it to \( map ... ) but that would
> seem to be clearly inferior to [ map ... ].   

It's certainly inferior in the sense that it does seems to do the same
as option C, and is therefore not what you want.

HTH

-- 
Brian Raven 

______________________________________________________________________
This email has been scanned by the MessageLabs Email Security System.
For more information please visit http://www.messagelabs.com/email 
______________________________________________________________________

_______________________________________________
ActivePerl mailing list
[email protected]
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to