|No such thing as a small change|
Curious Perl Behavior...by ack (Deacon)
|on May 25, 2010 at 21:04 UTC||Need Help??|
I recently finished reading the new addition of "Effective Perl Programming: Ways to Write Better, More Idiomatic Perl", 2ed, by Joseph Hall, Joshua McAdama, and brian d foy. It is a throuhly delightful read (see my review in the "Reviews" section of the Perl Monks site) and I have begun going back through it to explore the multitude of good examples. I have run upon a curous behavior that seems to defy the wisdom in one place in the text.
The example is drawn from Chapter 4: Subroutines on Item 46: Pass references instead of copies. The example is as follows:
Versus a version that passes references, a la:
In the text the authors state that in the firs case "Perl has to copy 100,000 elements in @numbers in sum, although it doesn't change any of the values. Perl does a lot of work for no good reason...A small change in the subroutine fixes that." And that results in the second examle of sum.
So I coded each up and decided to see just how much difference it made. I used the module Time::HiRes using the following code:
and got the following results:
So far, so good...exactly as the authors contended...not as dramatic a difference as I had imagined, but clearly consistent with the authors' position.
Ever the curious type, I decided to try a more dramatic case...I decided to try it with 1,000,000 numbers. When I did, I got the following unexpected result:
The first part of the result seems logical to me since it uses more numbers and is appropriately greater (timewise) than the first test cases offered by the authors. But the performace of the second version of my 1,000,000 number case is most curious, unexpected and inexplicable to me: the pass-by-ref case takes almost 40 times LONGER than the pass-by-copies case! Anyone got some insight into why that happens?
For reference I am running on Windows XP (Version 2002 Service Pack 3) on an Intel Core 2 CPU 6300 running @ 1.86 GHz with 3.49 GBytes of 1.86 GHz RAM. I am using ActiveStates v5.8.8 Build 820 Perl.
UPDATE: Thanks everyone for the responses. Seems I wasn't timing what I thought I was timing. Thanks especilly to linuxer and BrowserUk for your help. I was inadvertantly timing the creation of the references rather than how long it took to process with and without them. Their results restored the truth and are consistent with what the authors' thesis was. Thanks, again, for the help.
ack Albuquerque, NM