placing method calls in parameters vs creating a variable and passing it - java

When passing a value to a method,
place a method call directly in it which returns the required value to be passed
or create a variable and get the value in it through the same method call and place the value in parameter.
//first approach
methodToCall(methodReturnValue());
//second approach
int variable=methodReturnValue();
methodToCall(variable);
which technique is better?
In my own opinion I think the first technique is better than the second one because the second one requires you to create an extra variable which will definitely occupy memory space. Another aspect is, creating a variable causes a CPU cycle to memory while return value is stored in register not in memory(RAM) so it also reduce memory read cycles.

Option 1 has no "additional" runtime "penalty" whatsoever; there is no variable assigned, nothing that would need further treatment.
Option 2 on the other hand is easier to read (as the sequence of method calls is top down, instead of right to left); and it allows you to further use that result variable; for example for tracing or other functional calls.
Thus: the answer is - there is no better solution here. Just different options with different pros/cons.

Related

How to get anonymous values from a thread's stackframe (Java Debug Interface/JDI)

Note: This is regarding the Java Debug Interface (JDI).
I know there's the option to get a thread's stackframe, and from that a list of all visible variables and their values. However, I don't know how to get anonymous values, that is values not stored in a variable but "internally" on the stack (or maybe something else?).
Things like results from if-evaluations, comparisons, etc. For instance let's say we have this in our code:
if(array[i] > x)
How/where is that piece of data (i.e. the result: true or false) stored at runtime and what classes or methods within the JDI provide me access to it?
Thanks
The only way I know to get them without dropping down to debugging at the bytecode level is to change your code to assign them to a variable. Sorry, but that's the way it's designed; if it doesn't have a name it doesn't necessarily last long enough to get out of the execution stack and into a variable, and the debugger is designed to work on the latter, not the former.
Or ask the debugger for the values of x, i, and (once you know i), array[i] and do the computation/comparison yourself.
Or, in this case, simply watch what branch the if takes.

Passing big objects references instead of small objects to methods have any differences in processing or memory consumption?

I have a coding dilemma, and I don't know if there's a pattern or practice that deals with it. Whenever I have to pass some values to a method, most times I try to pass only the needed objects, instead of passing the objects which are being composed by them.
I was discussing with a friend about how Java manages heap and memory stuff and we didn't get anywhere.
Let me give two examples:
//Example 1:
private void method doSomething(String s, Car car, boolean isReal){...}
...
String s = myBigObject.getLabels.getMainName();
Car car = myBigObject.getCar();
boolean isReal = myBigObject.isRealCar();
doSomething(s, car, isReal);
//Example 2 - having in mind that BigObject is a really big object and I'll only use those 3 atributes:
private void method doSomething(BigObject bigObject){...}
...
doSomething(myBigObject);
In the 2nd example, it seems to me memory will be kind of wasted, passing a big object without really needing it.
Since Java passes only references to objects (and copies them, making it technically pass-by-value), there is no memory overhead for passing "big objects". Your Example 1 actually uses a little more memory.
However, there may still be good reason to do it that way: it removes a dependency and allows you to call doSomething on data that is not part of a BigObject. This may or may not be an advantage. If it gets called a lot with BigObject parameters, you'd have a lot of duplicate code extracting those values, which would not be good.
Note also that you don't have to assign return values to a local variable to pass them. You can also do it like this:
doSomething(myBigObject.getLabels().getMainName(),
myBigObject.getCar(),
myBigObject.isRealCar());
You're already only passing a reference to BigObject, not a full copy of BigObject. Java passes references by value.
Arguably, you're spending more memory the first way, not less, since you're now passing two references and a boolean instead of a single reference.
Java uses pass by value, when ever we pass an object to a method keep in mind that we are not going to pass all the values store in side the object we just pass the bits( some thing like this ab06789c) which is the value of the address on which the object is stored in memory(Heap Memory). So you are wasting more memory in first case rather than the 2nd one. Refer to JAVA pass-by-reference or pass-by-memory
All references are the same size, so how could it use more memory? It doesn't.

Should we pass argument to a method as a variable or as a new object directly in java

Consider the following two calls to the same method in java:-
1) doSomething(new Object[]{"something"}) ;
2)
Object[] obj = {"something"} ;
doSomething(obj);
Which one is more efficient in terms of memory and time efficiency ? I would say the 1) is better in both memory and time efficiency. Reason being in the second option requires us to create another variable (extra memory) and then assigns that value to the variable (extra time). Any comments ?
Just to clarify the object will be create only once, i am talking about the extra variable being used to hold the address of the newly created object.
Both are the same in terms of time and memory. The extra assignment can be optimized away by the compiler.
A difference is that the second version gives you an opportunity to give a useful name to your variable, which can make the code more clear.
The second call allows you to reuse the object in the calling method, but the first one does not.
It has no incidence on memory, as the passed object is created anyway.
You should always consider what is simpler and clearer first. You should only consider performance when you know you have a problem because you measured it in a profiler or micro-benchmark.
The best option is likely to be to use varargs
doSomething("something");
void doSomething(String... args) { }
Note: not only is the this simplest, but it is also potentially the fastest as the JIT can eliminate the String[] created.

Memory Effecient Object creation in Java

I have a basic doubt regarding object creation in java.Suppose i have two classes as follows
Class B{
public int value=100;
}
Class A{
public B getB(){
return new B();
}
public void accessValue(){
//accessing the value without storing object B
System.out.println("value is :"+getB().value);
//accessing the value by storing object B in variable b
B b=getB();
System.out.println("value is :"+b.value);
}
}
My question is,does storing the object and accessing the value make any difference in terms of memory or both are same?
They are both equivalent, since you are instantiating B both times. The first way is just a shorter version of the second.
Following piece of code is using an anonymous object. which can't be reused later in code.
//accessing the value without storing object B
System.out.println("value is :"+getB().value);
Below code uses the object by assigning it to a reference.
//accessing the value by storing object B in variable b
B b=getB();
System.out.println("value is :"+b.value);
Memory and performance wise it's NOT much difference except that in later version stack frame has an extra pointer.
It is the same. This way: B b=getB(); just keeps your code more readable. Keep in mind, that object must be stored somewhere in memory anyway.
If you never reuse the B-object after this part, the first option with an anonymous object is probably neater:
the second option would need an additional store/load command (as Hot Licks mentioned) if it isn't optimized by the compiler
possibly first storing the object in a variable creates slight overhead for the garbage collector as opposed to an anonymous object, but that's more of a "look into that" than a definitive statement of me
If you do want to access a B a second time, storing one in its own variable is faster.
EDIT: ah, both points already mentioned above while I was typing.
You will not be able to say the difference without looking at the generated machine code. It could be that the JIT puts the local variable "b" onto the stack. More likely however that the JIT will optimize b away. Depends on the JRE and JIT you are using. In any case, the difference is minor and only significant in extremely special cases.
Actually there is no difference in the second instance you are just giving the new object reference to b.
So code wise you cannot achieve the println if you use version 1, as you dont have any reference as you have in the second case unless you keep creating new object for every method call.
In that case the difference, if any, would not be worth mentioning. In the second case an extra bytecode or two would probably be generated, if the compiler didn't optimize them away, but any decent JIT would almost certainly optimize the two cases to the identical machine code.
And, in any event, the cost of an extra store/load would be inconsequential for 99.9% of applications (and swamped in this case by the new operation).
Details: If you look at the bytecodes, in the first case the getB method is called and returns a value on the top of the stack. Then a getfield references value and places that on the top of the stack. Then a StringBuilder append is done to begin building the println parameter list.
In the second case there is an extra astore and aload (pointer store/load) after the getB invocation, and the setup for the StringBuilder is stuck between the two, so that side-effects occur in the order specified in the source. If there were no side-effects to worry about the compiler might have chosen to do the very slightly more efficient dupe and astore sequence. In any case, a decent JIT would recognize that b is never used again and optimize away the store.

When to use field variable?

Under what circumstance would you use field variable instead of local variable? I found it a bit hard to decide when a variable is used in 2 or more methods in a class. I tend to use local variables and pass them to another method.
Thanks,
Sarah
In object-oriented terms, does the variable make sense as an attribute of the object? If so, you should make it a field variable. If not, it can go either way.
Remember the Single Responsibility Principle -- well-designed classes should have only 1 responsibility, and thus only 1 reason to change.
A field denotes some kind of state related to an instance of your class. For instance, a BankAccount could have a balance field.
You should never use a field to simplify passing data from one method to another method. That's simply not its purpose. Doing so also makes your methods intrinsically thread unsafe or require synchronization.
A local variable is just a temporary store of data used to support an operation being done by a method. For example,
public void addInterest(double rate) {
double toAdd = rate * balance;
logTransaction("Interest", toAdd);
balance += toAdd;
}
toAdd here makes no sense as a field since it is temporary to the operation, not a part of the account's state.
I would definitely not pass variables around to other methods unless there's a very specific reason. If the variable is used multiple times in the class, make it a field variable. This almost always makes your code much more flexible too.
In general, you can also think if the variable makes sense as a part of the class. That is, it makes sense to have a Car class have the variable numOfMiles, even if it's only used a few times. However, if one method is int GetAmountOfGasUsed(int milesThisTrip) it makes sense to pass in the miles variable as a local variable because the distance you travel is probably not specific to the car.
If the methods that use the variable need to modify the value as well, then by all means make it a field variable. But, if they only read the value, you can safely pass it around.

Categories