Thursday, June 7, 2012

Sonar or FindBugs Critical issue: Performance - Method concatenates strings using + in a loop

This issue arises when there is a String being built in a concatenation loop.
For each iteration, the String is converted to a StringBuffer/StringBuilder, appended to, and converted back to a String. This can lead to a cost quadratic in the number of iterations, as the growing string is recopied in each iteration.

Better performance can be obtained by using a StringBuffer (or StringBuilder in Java 1.5) explicitly.

For example:

// This is bad
String s = "";
for (int i = 0; i < field.length; ++i) {
   s = s + field[i];

// This is better - StringBuffer is synchronized
StringBuffer buf = new StringBuffer();
for (int i = 0; i < field.length; ++i) {
String s = buf.toString();

//Even better - better performance if synchronization is not an issue
StringBuilder builder = new StringBuilder();

for (int i = 0; i < field.length; ++i) {
String s = builder.toString(); 

Eclipse - Failed to load the JNI shared library

Eclipse started to fail during the opening of it, showing a pop-up window saying "Failed to load the JNI shared library". I did not know what was this and started to look on the web.

Eclipse failed to load the JNI shared library
Eclipse "Failed to Load the JNI shared library"

I've found out that this was a compatibility issue with jre/jdk 32 bit on a 64 bit machine.
I was running Eclipse 64 bit, with Windows 7 64 bit...
I remembered that I had installed a new software recently... and that installation added a jre 32 bit in the begining of my path. Due to this, Eclipse 64bit was being launched with a 32bit jre, causing that pop-up to appear.
Removed the jre 32 bit from the path, and then I was able to launch Eclipse again, like before!

Problem solved.