Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
PerlMonks  

Re: passing refs to subs

by indigo (Scribe)
on Oct 10, 2000 at 00:54 UTC ( [id://35991]=note: print w/replies, xml ) Need Help??


in reply to passing refs to subs

You have to ask yourself what is slower...passing the array/hash, or the extra deference everytime you assess it. Typically, passing by reference is a win, but now always.

Remember:
$foo{'bob'};
is faster than:
$bar->{'bob'}; # Slower, extra dereference
So if you have a small array/hash, and dereference it alot, code it both ways, and see what Benchmark tells you. I'm betting the difference will be small enough, you should be optimizing for readability instead.

Also, remember using reference allows you to modify the actual variable, where normally you will just modify a copy. This, and not performance, will usually determine which you should use.

Replies are listed 'Best First'.
(Ovid) RE(2): passing refs to subs
by Ovid (Cardinal) on Oct 10, 2000 at 01:47 UTC
    Also, remember using reference allows you to modify the actual variable, where normally you will just modify a copy.

    I'm sure you understand what really happens in a sub, but your wording is a bit vague, so I'll clarify this for monks who might not be familiar with this issue.

    You will only modify a copy of a variable passed to a sub if you copy the arguments to new variables. If you modify the @_ array directly, you modify the original variables. Run the following snippet to see what I mean:

    #!/usr/bin/perl -w use strict; my $test = "Hi there!"; change($test); print $test; sub change { $_[0] = "Hey, this is different!\n"; }

    Cheers,
    Ovid

    Join the Perlmonks Setiathome Group or just go the the link and check out our stats.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://35991]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others scrutinizing the Monastery: (6)
As of 2024-04-20 02:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found