Reputation: 979
Suppose I have an object ClassRoom, in the ClassRoom there are many Student objects (50 objects) with more than 20 properties, many Teacher objects (10 objects) with more then 20. ClassRoom also has some other properties like classNo, seatCapacity, etc.
Is it good to pass a object of ClassRoom object as an argument to a method. Suppose I need only 3-4 properties of ClassRoom and 1-2 properties of each Students. If it is bad, what is the cost of passing a heavy object.
Upvotes: 1
Views: 2157
Reputation: 108
There is no difference.The object is in a heap memory, and you're just using the reference to the object in stack memory.
Upvotes: 1
Reputation: 1254
I think that the JVM manages it for you, so you won't feel any performance problems, plus you're not passing the whole object by value, but you pass the object reference by value (kind of copy of a pointer). Hope it helps.
Upvotes: 0
Reputation: 121998
Forget about the memory, that's negligible. The answer is depends . Just pass based on your business logic instead of thinking about memory and yes JVM deals it better.
If you don't want the other method modifying the fields of your object, then don't pass the object. Just pass the required properties. If not, then its better to pass the object reference and use the values from it instead of adding those many parameters in method signature.
Upvotes: 1
Reputation:
In Java you are passing a reference to object. And there's no cost difference when you pass a String
instance or a complex class instance, like your ClassRoom
class.
Upvotes: 4