I want to optimize my Java source code, but I am not sure what parts of my code may be optimized. Is there any tool or any technique through which I can optimize my Java source code?
I know the basic fundamentals of code optimization, but I have a large number of lines and very complex source code (Java classes).
Can I optimize my code with the help of a Java profiler?
Thanks in Advance!
What do you mean by optimising your code? DO you want to refactor your code to simplify it. In that case I suggest you use your IDE to help refactor the code.
If you want to minimise its memory / CPU consumption, I would suggest you use a profiler like VisualVM or YourKit to idenify where resources are being consumed.
A code analysis tool can also help pick up the obvious performance issues. I have code analysis on as I type in my IDE which helps me pick up those issues as I write it.
Performance optimization - yes, a profiler may help. At least it can show you those areas in your application that take an unexpected amount of CPU time.
But before starting to apply changes - take care not to do some microoptimization. Look at improving algorithms first. Sometimes we use nested for loops while a task can be done with a single one (linear time). Double check if you use the correct collection types. Then have a look if you accidentally create more objetcs than needed (object creation in loops is a typical reason for performance problems).
Their are several tools for static code analyzes (to do code style / code convention / best practises / bug "optimization" of your code).
Checkstyle
PMD
Findbugs
I would recommend using Sonar. It covers them all and is easy to setup - even on a local machine (unzip and start). It is best used with maven projects but also possible for NON maven projects.
Related
I'm looking for JAVA cpu cycles counter.
I want to run test and see that it invoke some 2321 operations/cpuCycles, then optimize my code and see 3515 operations. So that I knew that I made mistake.
each time I will run the test it will have always same value until I modify the code.
Is there any feature that can help me with this?
Regards.
Number of operations does not tell you anything. I advise you consider JMH framework which is designed for micro-benchmarking java methods so you can run two implementations and compare time and memory consumption.
There is library description
http://openjdk.java.net/projects/code-tools/jmh/
Introducton from author
https://shipilev.net/blog/2014/nanotrusting-nanotime/
Detailed samples (open files one by one and read comments)
http://hg.openjdk.java.net/code-tools/jmh/file/tip/jmh-samples/src/main/java/org/openjdk/jmh/samples/
And there is IJ plugin (though, its usefulness is under the question)
https://github.com/artyushov/idea-jmh-plugin
In order to learn more about testing, we're going to use a profiler on a larger project (to actually get some values and measurements) and since we don't have any large project ourselves, we're forced to use something else. Any good suggestions? Maybe testing JUnit perhaps? (not "With" JUnit)?
Edit:
Not looking for any specific data, just... something... The problem is that all of this is so new so it gets kinda confusing. The point is to get slightly accustomed to testing tools such as a profiler. In other words, there shouldn't be too necessary to know much about the actual program since the program don't really matter and the data gained isn't too significant either and is mostly supposed to merely demonstrate that you can actually get stuff out of testing. So it's a bit confusing how I should proceed since I am not used to big actual programs.
Can I just download normal java files and just run/profile them with NetBeans (or similar) without having to do or care about a bunch of stuff?
Well, I've got my standard scenario. It's in C++, but it shouldn't take more than a day or two to recode it in Java.
Caveat: The scenario is not about measuring, per se, but about performance tuning, which is not at all the same thing.
It makes the point that serious code often contains multiple performance problems, and if you're really trying to make it go fast, profilers are not necessarily the best tools.
It depends on what type of data you want to profile. But the best way to get a "larger project" if you don't have one, is to find some open source project on the web that fit with what you want.
Edit: I never profile with NetBeans, so I can't tell you for this tool, but if you don't care about the tool, you can start trying with VisualVM (included with the JDK), it's a tool for monitoring the JVM. It's very usefull, and if you already run java application (like NetBeans) you'll not need to download extra applications.
Description of the tool taken on their website: VisualVM monitors application CPU usage, GC activity, heap and permanent generation memory, number of loaded classes and running threads.
VisualVM website
If you really want to profile with some source code, a little java application with a main will do the job, but again it depends on what data/amout of data you want to profile. Maybe you can find some "test applications" written in java on the web.
I am considering runtime byte-code generation/modification for a Java project.
Two important, and still maintained, APIs are ASM and Javassist.
ASM is the fastest at generating the code, and probably the most powerful. But it's also a lot less user-friendly than Javassist.
In my case, I want to perform the bytecode manipulation upfront, so that it is complete at the end of the application setup phase. So the speed of manipulation/generation is not critical. What is critical, is the speed of the generated code, because it will be part of a real-time desktop game, not the typical web-app, where the network delays hide the costs of reflection completely.
So my question is, does Javassist introduce some unnecessary overhead in the byte-code, which would not be present when using ASM? Or, expressed another way, is working at the ASM level going to provide me with a speed boost in the generated code compared to working with Javassist?
[EDIT] I'm interested in the newest version of both tools, and mostly interested to see if anyone tried them both on the same problem, and saw any significant difference in the speed of the resulting classes.
I don't think it would be possible to provide a simple objective answer to this. It would (I imagine) depend on the versions of the respective tools, the nature of the code you are generating, and (most importantly) whether you are using the respective tools as well as they can be used.
The other thing you should consider is whether going down the byte-code manipulation route is likely to give you enough performance benefit to compensate for the increased software development and maintenance pain. (And that can't be answered by anyone but yourself ...)
Anyway, my advice would be to only go down this route if you've already tried the "pure Java" approach and found it to give unacceptable performance.
How can I trace a Java program performance? Example, how long each method takes? How many resources were used and so on? I need some info for me to work on optimizing my Java program.
As others previously mentioned, profilers are the go. A long time ago, I'd used http://www.yourkit.com/, and found it quite easy to use and informative.
If you are keen, you could investigate using AOP for method timing etc. Just search Google for AOP method timing for some ideas.
You could try opening your project in Netbeans, from there you can use the Profiler tool and get performance data for methods, load times, etc. It's really easy to use and the data is very complete.
Netbeans Profiler
You can try a JVM profiling tool such as JProfiler.
Making a good and robust benchmark in java is hard. Take a look at the following articles:
http://www.ibm.com/developerworks/java/library/j-benchmark1/index.html
http://www.ibm.com/developerworks/java/library/j-benchmark2/index.html
In optimizing, it's hard to tell what causes the slow performance. Usually a bad algorithm (complexity) causes it. Maybe you can start from the algorithm first before go into further detail tweak
I'm about to port a smallish library from Java to Python and wanted some advice (smallish ~ a few thousand lines of code). I've studied the Java code a little, and noticed some design patterns that are common in both languages. However, there were definitely some Java-only idioms (singletons, etc) present that are generally not-well-received in Python-world.
I know at least one tool (j2py) exists that will turn a .java file into a .py file by walking the AST. Some initial experimentation yielded less than favorable results.
Should I even be considering using an automated tool to generate some code, or are the languages different enough that any tool would create enough re-work to have justified writing from scratch?
If tools aren't the devil, are there any besides j2py that can at least handle same-project import management? I don't expect any tool to match 3rd party libraries from one language to a substitute in another.
If it were me, I'd consider doing the work by hand. A couple thousand lines of code isn't a lot of code, and by rewriting it yourself (rather than translating it automatically), you'll be in a position to decide how to take advantage of Python idioms appropriately. (FWIW, I worked Java almost exclusively for 9 years, and I'm now working in Python, so I know the kind of translation you'd have to do.)
Code is always better the second time you write it anyway....
Plus a few thousand lines of Java can probably be translated into a few hundred of Python.
Have a look at Jython. It can fairly seamlessly integrate Python on top of Java, and provide access to Java libraries but still let you act on them dynamically.
Automatic translators (f2c, j2py, whatever) normally emit code you wouldn't want to touch by hand. This is fine when all you need to do is use the output (for example, if you have a C compiler and no Fortran compiler, f2c allows you to compile Fortran programs), but terrible when you need to do anything to the code afterwards. If you intend to use this as anything other than a black box, translate it by hand. At that size, it won't be too hard.
I would write it again by hand. I don't know of any automated tools that would generate non-disgusting looking Python, and having ported Java code to Python myself, I found the result was both higher quality than the original and considerably shorter.
You gain quality because Python is more expressive (for example, anonymous inner class MouseAdapters and the like go away in favor of simple first class functions), and you also gain the benefit of writing it a second time.
It also is considerably shorter: for example, 99% of getters/setters can just be left out in favor of directly accessing the fields. For the other 1% which actually do something you can use property().
However as David mentioned, if you don't ever need to read or maintain the code, an automatic translator would be fine.
Jython's not what you're looking for in the final solution, but it will make the porting go much smoother.
My approach would be:
If there are existing tests (unit or otherwise), rewrite them in Jython (using Python's unittest)
Write some characterization tests in Jython (tests that record the current behavior)
Start porting class by class:
For each class, subclass it in Jython and port the methods one by one, making the method in the superclass abstract
After each change, run the tests!
You'll now have working Jython code that hopefully has minimal dependencies on Java.
Run the tests in CPython and fix whatever's left.
Refactor - you'll want to Pythonify the code, probably simplifying it a lot with Python idioms. This is safe and easy because of the tests.
I've this in the past with great success.
I've used Java2Python. It's not too bad, you still need to understand the code as it doesn't do everything correctly, but it does help.