mjoyce has asked for the wisdom of the Perl Monks concerning the following question:

I'm working on a project in which I'm using multiple instances of various Objects. There are times when one of these instances needs to be passed to another object's subroutine.

Is it more efficient (better practice?) to pass the object itself:
$myotherobject->subRoutine($object)

Or a reference to the object?
$myotherobject->subRoutine(\$object)

Thanks. Michele

Replies are listed 'Best First'.
Re: Efficiency Question
by kyle (Abbot) on Mar 25, 2009 at 19:23 UTC

    In your example, $object already is a reference that's been blessed into a class. That's all an object is—a blessed reference. Passing in a reference to that reference doesn't gain you anything.

      To be pedantic, you will take a hit from passing the object references since it will involve an extra ref/deref step. Of course, if that hit actually matters in any way/shape/form, either you or your code have some serious issues.
        OTOH, in addition to the insignificant performance hit, there may be a very significant maintenance hit. A future maintainer (maybe even the original author of the code!) may take a look at the superfluous ref/deref process, think "What the...?!?", and start looking through a ton of code for some clue as to why such a non-standard and round-about approach was used.

        The considerate thing to do is to avoid setting someone else (or, again, maybe even yourself) up for such a wild-goose chase.

Re: Efficiency Question
by JavaFan (Canon) on Mar 26, 2009 at 01:00 UTC
    Regardless of which one is more efficient, I wonder why you even care. You've already taken the decision to use Perl instead of, say C, and taken an gigantic efficiency hit. Once gone that way, care about using efficient algorithms. Don't do silly things which you think may save you a few microseconds. If those microseconds are important to you, do not use Perl. Perl is very well suited to do many things - but one thing it sucks at is creating the fastest solution to solve a problem. (It may create a solution faster than in C, but not a faster solution).
Re: Efficiency Question
by davido (Cardinal) on Mar 26, 2009 at 05:04 UTC

    The amount of time it took to compose the top level post is greater than the time difference between the two options you listed, over about a gazillion iterations. If you're trying to optimize code, you're probably looking in the wrong place here.

    Profiling your code will give you a better idea where you're spending most of your time. It's possible that you're IO bound, or processor bound, and if processor bound, it's probable that the bottleneck hasn't anything to do with whether you pass a blessed object ref, or a ref to a blessed object ref.


    Dave