DEV Community

Discussion on: Explain Return vs Passing Reference Like I'm Five

Collapse
 
tgc profile image
tgc

Hope this helps although it`s not %100 accurate

You have a 12 years old kid Johnny who likes chocolate cheese cake very much and if he does not eat everyday he gets very sad.

So everyday you go to your favorite bakery. This bakery has 2 options for you.

(1)If you order a standard chocolate cheese cake and they wrap it up for you it takes 16 minutes for you to leave the shop.15 minutes goes for baking and 1 minute for them to fold up the carrier box and putting the freshly cooked cake in it.Costs you $5 dollars

(2)If you bring your own carrier box which is already folded it takes just 45 seconds to package and costs $4.95.

Using (2 - Pass by reference)Johnny can take the first slice 15 seconds before when compared to (1 - Return value). And it`s less expensive (less cpu clock cycles)

It does not dramatically improve Johnny `s life and your budget but 15 seconds is 15 seconds and 5 cents is 5 cents.

If you are working on simple objects, the performance would be similar in both cases.

As he is a grooving kid next year Johnny starts to ask for a chocolate cake with a bagel and a lemonade. Seems like he is hungry for carbohydrates but anyway , you know kids:)

if you choose (1) you need to wait 3 minutes for packaging because now there are more items to be separately packed and it costs you $6.70.

However with the option (2) if you take your own lemonade cup , cake & bagel carrier boxes you can leave there in 1 minute by paying $5.50.

This time choosing (2) might have significant effect given that this is your routine and you are rushing to catch a bus.

If the object is so large and complex, returning it would need a copy, and it could be slower than having it as a referenced parameter, but it would spend less memory.