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?

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 ... ].

At 04:11 AM 4/10/2006, Brian Raven wrote:
>Alan M. Carroll <> wrote:
>> I went netsearching for this but couldn't find anything in all the
>> noise. 
>> 
>> 1) What is the runtime cost of the scalar operator? Is it constant or
>> does it depend on the size of the array? Is it different than
>> $#array?  
>
>Evaluating an array in a scalar context returns the size of the array,
>$#array returns the index of the last element. So, not the same.
>
>As for the cost, why does it matter if your code is fast enough?
>Seriously, it might help answer your question if we knew what problem
>you are actually trying to solve.
>
>C doesn't do what you want, so it gets disqualified from the contest and
>retires to the changing rooms in shame for an early shower. Did you try
>it, BTW?

_______________________________________________
ActivePerl mailing list
ActivePerl@listserv.ActiveState.com
To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs

Reply via email to