Reputation: 7310
Which is faster and/or less resources consuming:
class Foo()
{
public int value;
}
This way?
public int doSomeStuff(Foo f)
{
return (f.value + 1);
}
public int doOtherStuff()
{
...
Foo f = new Foo();
int x = doSomeStuff(f);
...
)
or this way?
public int doSomeStuff(int v)
{
return (v + 1);
}
public int doOtherStuff()
{
...
Foo f = new Foo();
int x = doSomeStuff(f.value);
...
)
In both cases, "doSomeStuff" will not change nothing in foo class. It just needs to know the "value".
Upvotes: 0
Views: 307
Reputation: 115328
It does not matter from performance perspective. The recommendation is: do not think about pre-mature optimization. Think about correctness and good design of your code.
For example your code
integer
. Choose among int
and Integer
Upvotes: 0
Reputation: 37506
The difference between doing:
object.intvariable + 1
and
int + 1
is so negligible as to be irrelevant for real world apps. It's probably one or two more JVM opcodes to look up foo and find its value variable which is not worth mentioning. You'd never notice that unless you were trying to create a pseudo real-time app in Java (which is all but an exercise in futility).
However, that said, the way you are doing it is very bad. You should not be exposing value
directly, but be using proper data encapsulation via getter and setter methods.
Upvotes: 0
Reputation: 178411
Probably even better:
Decalre doSomeStuff()
as a method of foo
, and invoke: f.doSomeStuff()
It is much more readable and will be easier to maintain doing it so, since if you have a
sub class of foo
: Bar
, and you want to calculate things a bit different - all you have to do is override doSomeStuff()
in Bar
You should prefer readability over micro optimizations - let the compiler take care of those for you.
code snap:
class foo() {
public int value;
public int doSomeStuff() {
return value + 1;
}
}
and:
public int doOtherStuff() {
...
foo f = new foo();
int x = f.doSomeStuff();
...
}
Upvotes: 0
Reputation: 47608
In terms of resource consuming, it is exactly the same. But the second option is clearly better in terms of programming because if doSomeStuff only needs value, then there is no point to passing f.
Upvotes: 1
Reputation: 36767
Depends how often you're going to call doSomeStuff
without calling doOtherStuff
, but generally performance difference is negligible and if you only call doOtherStuff
then they'll be equally performant.
Upvotes: 0
Reputation: 25873
I don't think there is any performance difference at all. And Java compiler will optimize to the best one anyway...
Upvotes: 0
Reputation: 47609
They both perform the same, the same sequence of operations occurs. Your main concern is maintainability and sensible design here. Think carefully about which methods need which data and design it properly.
If you do have issues, you can optimise later. But you should always optimise last.
Upvotes: 3