So I just concluded the 'Introduction to Java Applications' chapter in 'Java How to Program'. I'd probally be punching my computer cause of those damned environmental variables if not for the kind people here.
Anyways, one of the exercises in the end of the chapter is to put together an app that collects two numbers, then give the; sum, difference, product and quotient.
I put this together and it worked thankfully:
After it ran, I was wondering how I could shorten the length of the code, so I tried this:
I tried it out, and it worked. YAY ME, but I was wondering, which is more efficient.
I concluded the second one because there is no need to store the four solutions. As a result the first one ties up memory that could otherwise be used one something else. Am I right in this assumption? I know this is a meaningless app, and memory use means nothing for it. Just curiosity.
It does not really make any difference. In the last line, where you print all the results, Java will have to store the results of the calculations somewhere, so that they can be passed to the System.out.println method. Whether you store the results in named variables, or let Java store them somewhere, doesn't really make any difference at all for memory usage.
Don't worry too much about memory and performance optimization, especially if you're just beginning to learn Java.
Optimizing code is often much less intuitive than people think, because the compiler and the JVM do a lot of sophisticated optimizations below the covers, and sometimes people think they optimize things by changing their code, while they're really not, because they unknowingly make changes that make it harder for the compiler or the JVM to automatically optimize things. The only way to improve the memory or speed of a program is to use tools like profilers to measure where the bottleneck in the program is, try to improve that part of the code, re-run, measure again etc. Optimizing by just inspecting the source code and reasoning about it often doesn't work.
The other consideration is ease of understanding. Which can be a matter of opinion, but I think in the first piece of code it's clearer what you're doing and why you're doing it, because the variable names have meaning.
incandescent light gives off an efficient form of heat. You must be THIS smart to ride this ride. Tiny ad:
Try Free Java/.NET Libraries for Word Excel PowerPoint and PDF