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.
I would normally write that: for (my $ii = 0; $ii < @objs; ++ii) { ... } > One could then make it O(n) by doing > > my $limit = scalar(@objs); > for ( my $i = 0 ; $i < $limit; ++$i ) { ... } I'm not sure that this would gain you too much and if you don't need $i inside the loop, the foreach form would be clearer. > 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? I would normally use : if (@list) { > The question is, should I try to make a habit of one of these in particular? > Or does it matter? I'd not bother with '<= $#list' unless you need the last element - use '< @list' instead. I'd also not bother with 'scalar @list' unless you need to force context. _______________________________________________ ActivePerl mailing list ActivePerl@listserv.ActiveState.com To unsubscribe: http://listserv.ActiveState.com/mailman/mysubs