Re: Which is better, pass, or not pass by reference?
From: André Nęss (andrena.spamreallysucks_at_ifi.uio.no)
Date: 10/21/03
- Next message: Eric Veltman: "Re: How much are PHP programmers paid in Germany?"
- Previous message: Eric Veltman: "Re: How much are PHP programmers paid in Germany?"
- In reply to: Randell D.: "Which is better, pass, or not pass by reference?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Tue, 21 Oct 2003 19:58:48 +0000
Randell D.:
>
> Folks,
>
> I've asked this before but never got any response but its important and I
> thought I'd pitch it again (hopefully a bit clearer)...
>
> One can pass data from one function to another either by passing a copy,
> or passing by reference.
>
> My understanding of passing by reference (putting the & before a variable
> during the function declaration) means that the original data is used.
>
> My understanding of *not* passing by reference, (thus passing a copy)
> literally
> means creating a copy of the data contained in my variables - thus
> doubling the memory usage for this data... even if its just a temporary
> while the function is being executed.
>
> I *believed* (past tense) that one should only pass by reference if they
> wanted the child function to change the data and pass the newer values
> back to the parent function.
>
> I'm now thinking that this is just a feature and not the only usage. I am
> begining to think I should use "pass by reference" nearly all the time in
> order to conserve memory (since I won't be creating copies of my variable
> data in memory).
>
> Would this be good practice? Am I right that passing by reference means
> that my variable data is not duplicated thus using less memory than if I
> had passed my variable data as a copy?
That's very risky business IMO. At some point you're bound to forget about
it, and change a variable that was passed by reference. This can lead to
lots of hard to catch bugs. It is generally accepted that pointers are a
bad thing, and they should be avoided whenever you can. Functional
programming languages go farthest in this respect, and this also makes them
easier to program.
Also note that the PHP engine has some tricks up it's sleeve to avoid
unnecessary copying (http://www.zend.com/zend/art/ref-count.php), but I'm
not sure if this works with argument passing as well.
All in all I don't think it's worth the hassle. If memory is a problem you
should instead find the memory hotspots and optimize them, possibly
rewriting them in C.
André Nęss
- Next message: Eric Veltman: "Re: How much are PHP programmers paid in Germany?"
- Previous message: Eric Veltman: "Re: How much are PHP programmers paid in Germany?"
- In reply to: Randell D.: "Which is better, pass, or not pass by reference?"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|