in reply to Strange benchmark result that has me totally confounded

However, I'm still confused as to why there is such a dramatic change.
That's easy. You change your original items in @messages, so after one replacement, there's nothing left to replace.

Add

my @messages = @messages;
at the top of each routine, and the difference becomes much less... Roughly around 22% of difference, just for the 2 extra substitutions.

Replies are listed 'Best First'.
Re: Re: Strange benchmark result that has me totally confounded
by jpfarmer (Pilgrim) on Apr 16, 2004 at 22:45 UTC

    But I'm not modifying @messages, am I?

    Unless I'm missing something, I'm only modifying $post. The value of @messages isn't touched during the foreach loop because data from the array is copied into the scalar.

    That said, I see a change in performance as well when I use local to create a copy of @messages, and I just don't get it.

      But I'm not modifying @messages, am I?

      Surprise! You are, due to the magic of variable aliasing:

      my @messages = <DATA>; foreach my $post ( @messages ) { $post =~ s/ /-/g; } print @messages; __DATA__ one foo bar three words here

      As perldoc perlsyn says:

      In other words, the "foreach" loop index variable is an implicit alias for each item in the list that you're looping over.

      I don't think local will do it either; not unless you want an empty array or are doing something a lot more clever than I can imagine. You need to reset the values of the array for each benchmark iteration.