Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 7 years ago.
Improve this question
There is an explanatory code of what I'm trying to ask. Sureley, the difference between the codes below is ignorable, yet it describes the point.
Which one is the most efficient in terms of memory usage and performance?
if( MathUtil.CalculateSin(angle) > Angles.ACUTE){
// Something is done
}
or
double angleSin = MathUtil.CalculateSin(angle);
if( angleSin > Angles.ACUTE){
// Something is done
}
It simply depends if you are going to re-use the variable.
If yes, use the second case.
If no use the first case.
There is no reason to store the value in a variable if you are not going to re-use it.
Edit :
As per your comment, it seems you are mostly asking this question for performance concern...
Actually my question is not about the algorithm nor the way I
implement it. I'm curious about the memory usage of the approaches,
therefore efficiency is the purpose.
Don't expect any difference in term of memory usage for both approaches, the JVM and JIT will optimize it as much as possible so that both case become the same.
To extend the other answers, you should also consider readability of your code. In this case, the meaning of MathUtil.CalculateSin(angle) is pretty obvious. However, if you have a more complex condition, it would be a good idea to precompute that condition, give the variable a meaningful name and then use the variable in the if-statement.
In your case it also depends on the context of the if-statement. Again, MathUtil.CalculateSin(angle) > Angles.ACUTE is quite easy to grasp at a glance. However,
final boolean angleIsAcute = (MathUtil.CalculateSin(angle) > Angles.ACUTE);
if(angleIsAcute) { ... }
would carry the meaning better. In this case, of course, both possibilities are quite similar, but I hope you see where I am going with this.
Do not worry about the overhead that is introduced by storing that extra variable. Even though the java-compiler does not optimize your code, any JVM worth its salt will optimize the bytecode and the performance overhead will be negligible.
I often use the first pattern even when I won't need the variable later in the code. The advantage is for debugging.
You can examine and change the value of the variable when stepping through the code in a debugger.
If an exception occurs in the call on the right-hand side of the statement, it is sometimes clearer what happened than if the call is embedded in an if or as an argument to another call.
If you're concerned about memory usage for the variable, don't be. Trust the compiler to optimize away variables that it knows aren't going to be used later. If you declare the variable final, it will be optimized aggressively as described in the JLS.
References do take memory. So if you are not going to use angleSin anywhere else then second option is what you should go for. Besides it does not pollute the namespace. That is one reason people make Comparator as an anonymous class instead of creating a new one. If they do not need to use somewhere else.
Related
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
do you prefer writing method with immediate return of result to assigning it firstly to variable? To be clear we only consider situation presented below when no other operations are done in method body.
First option:
private List<Integer> getIdsOfUsersLoggedWithinLastHour() {
return userDAO.getUsersLoggedWithinLastHour().stream().map(User::Id).collect(Collectors.toList());
}
Second option:
private List<Integer> getIdsOfUsersLoggedWithinLastHour() {
List<Integer> ids = userDAO.getUsersLoggedWithinLastHour().stream().map(User::Id).collect(Collectors.toList());
return ids;
}
IMHO there is no need to assign result of method operations to variable when you do nothing with it and just return. The return type is declared in method signature so you can easily check it. The code cleanliness is about the same. You use some additional memory and cpu operations (maybe not so important today but it is always something additional). Friend of mine claims that initializing variable is better for easier debugging and further code development but I think it is redundant and can be done when you really need this, not 'for future'. What is your opinion?
In many cases I plump for the second option and, in the cited case, I almost certainly would.
This allows you to place a breakpoint on return ids; which can be helpful when debugging. (Inspecting the contents of a CPU register is an option in low level languages like C, but I don't think that is available for JVM-based languages).
A series of functions that return an anonymous temporary up the stack can be difficult to debug.
I wouldn't worry about any overhead that the second choice introduces: that ought to be optimised out and declaring an extra reference variable is unlikely to cause a performance bottleneck even if it was not optimised out. (Note that in C++ it will be optimised out via a process called Named Return Value Optimisation and I imagine that Java would follow suit.) Remember that being able to debug and maintain code is as important as elegance; whatever that means in this particular instance.
I assign result to the variable only when need to do some logic with it before returning value from the method. Otherwise I use coding style from the first example - makes code concise.
Second code style can help during debug process sometimes, but you shouldn't commit this IMHO
Also, if you inspect second example with any popular static analysis tool it would give a result like "local variable is redundant" which is one more reason to eliminate those vars in real projects.
Good article about this design issue: http://www.yegor256.com/2015/09/01/redundant-variables-are-evil.html
But you must understand that it's only a common practice, nobody can make you do not use redundant variables - code works with them correctly, it's only a question of taste like many other design principles
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
The following example is tailor made to make my doubts clear.
EG: WAP, with a method getAllWordsStartingInputChar to return the frequency of a word in the dictionary. The dictionary in form of a hashmap would be provided to the constructor.
Now, before getAllWordsStartingInputChar is called for the first time, I need to create another map of char->list of words begining with that char
Where should this map be created ?
In the constructor ?
Lazy initialization ?
Anything else ?
Please try to avoid being specific about my example, the idea i am trying to convey is 'some computation that needs to be done, whose results would be stored and used over and over again'.
Where should such computation be done.
Please try to avoid being specific about my example
Thats's no problem, because I cannot be too specific about this example when the example itself is not very specific (just kidding a little).
Seriosly, there is no problem to initialize a HashMap in the constructor
as long as you don't start a thread which uses these variables or call a method which do that or, also evil, call a overridable method in the constructor. Probably I forgot something.
Strategie of creation
If your Map list of words beginning with that char is used in each case, which means, there is no case in which you don't need the map, than you should create it during construction.
If these map is used very seldom, chose lazy initiaization, e.g. at the first call of a getter.
That is just my opinion without knowing very much about your needs.
Where should this map be created ?
1) In the constructor ?
Possibly.
2) Lazy initialization ?
Possibly.
3) Anything else ?
Probably not.
In purely performance terms, the choice between 1) and 2) depends on the probability that the constructed object won't use the second map. You need to balance the cost of the laziness (extra tests each time the map is used) versus the cost of creating the map unnecessarily.
The only "anything else" that I can think of is creating the second map each time that you use it. That only makes sense from a performance perspective if the map is only ever used zero or one time.
Where should such computation be done.
From a performance perspective, that's probably not relevant. From a design perspective ... you can make make a variety of arguments about where the code belongs. It is a matter of personal taste (IMO).
But looking back at the above comparison of 1) versus 2), the other observation is that this smells of "premature optimization", and premature optimization is often a complete waste of time. For more on that topic, read this: https://softwareengineering.stackexchange.com/a/80092/172.
If you have perfect information of how the costs will work out in practice, then the optimization is just "maths". But in practice, you rarely have enough information, and the mathematics is frequently too complicated. And general "rule of thumb" answers are not going to be reliable. Hence, each situation needs to be optimized on its merits ... based on real performance measurement. (If the effort is warranted!)
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
If I have a series of method invocations, the value of each used for the next call, should I store them in local variables, like so:
DynamicForm filledForm = Form.form().bindFromRequest();
String shareIdStr = filledForm.get("data[shareId]");
UUID shareId = UUID.fromString(shareIdStr);
Share share = Share.find.byId(shareId);
or as a single invocation chain, like so:
Share share = Share.find.byId(UUID.fromString(Form.form().bindFromRequest().get("data[shareId]")));
In this case, the only value that is used again is share. Perhaps the answer is somewhere in-between, or is something completely different. What's your opinion?
Not chaining Methods :
ADV
Enhances readability.
Gives an opportunity for re-usage.
Pin pointing exceptions (if any) becomes easier.
Debugging becomes easier, i.e. setting breakpoints on specific invocation is easy.
DisADV
Increases length( I wont say size :) ) of code.
IDE warnings (if any).
Chaining Methods
ADV
Reduces the need for creating multiple temp. variables.
Is a syntactic sugar
Reduces the number of lines to be written.
DisADV
Reduces readability of code.
Commenting becomes difficult (if any) for particular methods called.
Debugging the whole chain of invocation becomes very difficult.
The first way is only useful if you re-use these variables later in the method. If not, Eclipse will tell you they are not used. So the second way is better, I think.
To clarify a long line of code, I like to write it like this :
Share share = Share.find
.byId(UUID.fromString(Form.form()
.bindFromRequest()
.get("data[shareId]")
)
);
You can only compare these two forms if you consider you will not reuse variables. Otherwise, it doesn't make sense to compare them.
Generally the first variant gives your code more readability and potentially makes it easier to maintain.
Personally I develop a lot for embedded systems where the target platform has big constraints on computation power and size. Therefore I typically inline the code, so that my bytecode is smaller.
If I am to develop an application to run on a powerful server, or even the regular PC, then I would most likely opt for variant one.
Depends how you want to read your code. Local variables are useful if you are going to use them again. Otherwise proceed with chain invocation.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
In Java, say I have an expression X that occurs multiple times in a function. Generally speaking, is it more efficient to create a variable and set it equal to X, or not use a variable at all? What are the advantages/disadvantages of each method?
Ex. Say X = 5+9*9-1000. Which function is more efficient, function1 or function2?
public void function1() {
System.out.println(5+9*9-1000);
System.out.println(5+9*9-1000);
}
public void function2() {
int variable = 5+9*9-1000;
System.out.println(variable);
System.out.println(variable);
}
Neither is more efficient. Your expression 5+9*9-1000 is a constant expression. The compiler will evaluate it at compile time and only the result shows up at runtime (-914).
The JLS defines constant expressions in Section 15.28. Basically it consists of literals, operators, and constant variables.
Often it's more convenient, readable, and expressive to have a constant expression rather than multiplying the values yourself.
int secondsPerDayCalc = 86400; // not obvious it's number of seconds in a day
int secondsPerDay = 60 * 60 * 24; // constant expression; more readable
There is no performance penalty, because it's evaluated at compile time.
Use a variable in this case or a function in more complicated cases. Yes, there may be an efficiency gain, but the real issue is the maintainability of the code. Repeated strings of characters like this create a source of potential errors if the expressions need to change.
Generally speaking, is it more efficient to create a variable and set it equal to X, or not use a variable at all?
Generally speaking, it is not possible to say. It may be more efficient. It may make no difference. It could conceivably even be less efficient. It all depends on what the JIT compiler does with the code, and that is dependent on the JVM you are using, the application, and even the input data.
(In your specific example, the expressions are constant expressions, and they will be evaluated at compile time. That makes the runtime efficiency issue moot.)
What are the advantages/disadvantages of each method?
To my mind, the most important issues are:
Readability. Splitting an expression into sub-expressions with temporary variables may make your code more readable. (It depends on the code complexity ... and the expected Java reading skills of the people who need to maintain your code.)
Side-effects. Some expressions involve side-effects. In this case, refactoring to use temporary variables may change the meaning of the computation.
The best general advice is to leave this kind of optimization to the JIT compiler. But if performance is an critical issue, and you do really need to optimize at this level, then you need to do it scientifically.
Benchmark your code (properly!) to establish a performance baseline.
Profile it to identify hotspots.
Modify the code to improve performance at a hotspot.
Rerun the benchmark to see if you have improved things.
Go to step two ...
(Optimizing based solely on your intuition, you are liable waste a lot of your time optimizing with minimal measurable performance benefits. Also bear in mind that hand optimizing for one platform does not necessarily improve performance on others ...)
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 11 years ago.
Improve this question
There seems to be two accepted variable declaration placements for Java variables, each with different raison d'ĂȘtre.
From the Sun's code conventions we can see:
Put declarations only at the beginning of blocks. (A block is any
code surrounded by curly braces "{" and "}".) Don't wait to declare
variables until their first use; it can confuse the unwary programmer
and hamper code portability within the scope.
However in the highly praised "Code Complete" and some other authors advocate for reducing the scope of a variable to a minimum. That is basically waiting to declare variables until their first use.
These two approaches are clearly contradictory although I can see the point for both of them.
Which should I follow? Is there any consensus on the matter?
Variables should be declared as close to their use as possible, for two reasons:
Vertical locality
Tool hinting
Vertical locality makes it easier to reason about chunks of code. The less scanning a reader has to do the easier it is to understand what code does, and what side-effects it
Reducing variable scope also allows better tool hinting for automated tools, like refactoring. The closer together related things are the more obvious they are.
That said: if a method is long enough that the above points come in to play, it's likely the method is already too long, and should be refactored anyway.
That is basically waiting to declare variables until their first use.
This is actually not true, and these two styes are not conflicting. Limiting the scope of the variable means that that variable, in fact, does not exist outside of that scope. E.g.
for(int i=0; i<10;i++){
int a = 5;
doSomething(a);
}
In this case, a is scope limited to the for block and this is what Code complete is referencing.
In any case I agree with sun, that variables within a scope (class, method, if block, etc.) should be declared at the beginning.
My personal opinion is that either way is fine. I think as long as the variable names are descriptive enough, it doesn't really matter. Again, this is only my opinion. I've had to go through lots of code which wasn't written by me, and the biggest frustration with variables I've faced, is that their names are not very descriptive. Most IDEs will have the option of 'go to definition' so it doesn't really matter where you declare them.
Those two statements do not need to be contradictory. Scope is decided by the curly brackets, so if you start a new set of brackets closer to where you use them, that is consistent with the Sun coding convention. Of course if you are just arbitrarily inserting scope limitations, that is a problem for reading the flow of the code.
However, I find it very important to declare fields at the top of the class, especially mutable fields. Understanding the state of an object can be the hardest part of a class over the long term, and putting the declarations at the beginning of the class clearly states what significant state the class holds.
I also recommend "Effective Java" by Joshua Bloch for more reasons why one should declare variables where they are first used.