let's say that I have a big main class with a lot of variables, subclasses, etc... in it. Like "IngameScreen"

What if this class is passed as a parameter very often for each frames ? For example there is a "playSound" function in it so every entity need to have this class injected to make a sound.

Does that affects performance ? Or is it something like "it's just a pointer so it costs pretty much nothing" ?

The language is Kotlin

  • 1
    \$\begingroup\$ Does your testing & profiling suggest that you have a problem here that you need to solve? \$\endgroup\$ – DMGregory Jul 10 '19 at 23:15

In Kotlin the size of the object passed via parameter does not impacted performance.

Here's why:

  • Kotlin is designed to be fully interoperable fully with Java.
  • Java alway uses pass-by-value.
  • In Java the value of an object is always a reference to the object.
| improve this answer | |

If you're passing by value it will involve allocating memory on the stack, copying over data, invoking the copy constructor, potentially creating more objects (which will have their own performance implications) and then undoing all of that on return.

If you're passing by reference it is just a pointer.

Is passing by value always slower? Depends on the object. If it's a simple object, like - say - a vec3, you're probably not going to even notice. If it's a complex object like a mesh with vertex buffers that needs to hit the disk during creation, then - ouch.

Sometimes passing by value is what you want, but that's going into more general programming territory which is maybe out of scope here.

So be sure that you know the characteristics of your objects and define an appropriate copy constructor if required.

| improve this answer | |
  • \$\begingroup\$ So you're saying that passing by value will potentially impact performance, while @Pikalek 's answer says that it does not impact performance at all. So who's right ? \$\endgroup\$ – user3491043 Jul 11 '19 at 7:45
  • \$\begingroup\$ @user3491043 - please note the context of Pikalek's answer: "In Java the value of an object is always a reference to the object". \$\endgroup\$ – Maximus Minimus Jul 11 '19 at 8:20
  • \$\begingroup\$ And the question is about Java so in the end, in the context of the question, it doesn't matter how big parameters are ? \$\endgroup\$ – user3491043 Jul 11 '19 at 8:24

Not the answer you're looking for? Browse other questions tagged or ask your own question.