简体   繁体   中英

passing parameter optimization in java

does it matter in java which parameters I pass to a method? For example, I have some methods for validation. Let's say I have a class Person holding personal information and one method in another class validating e-mail addressees. In my Controller class, where I use the Person and the Validator classes, should I pass the whole person object, or should I pass just the String with the email person.getEmail() . In the first option, the Person.validateEmail(Person person) method can call person.getEmail() . So, does it matter how 'big' the passed parameter is? I mean in terms of memory/cpu.

No, it doesn't matter, since all you are passing is a reference to the object in question. See this question and answers for the details.

The one exception is when the method call is remote, then the entire object graph has to be serialized. The time this takes depends on the number of fields and amount of data.

In java when you pass whole object of Person , you just pass an address of that object. So, doing that you are not coping entire object, only its reference.

In that case it doesn't matter in terms of performance what yo will pass: single email address or person object, which contains that email.

On the other hand it depends on how you will use that method in future. If this method is some kind of utility method, which does something with an abstract email, so it will be good interface solution to pass in it only String parameter with e-mail.

Java pass parameter as call by value , not call by reference. So In case of object its pass only address value of person class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM