Introduction
Java decompilers are great tools to give insight about efficiency of compiled code. Currently there are two popular java decompilers: cavaj and jd-gui.
Comparison Case
It is a well-known fact that concatenation of strings is not an efficient way of building strings using some number of other string obects. Since string objects are immutable, each concatenation creates a new string, this will continue until final string object is created. All created string objects other than the final one, are intermediate objects and nothing but garbage.
For this reaseon java compiler converts string concatenations into StringBuilder statements. Using decompilers lets see if this is really true.
Below are the original source code and decompiled versions of original code using two decompilers.
// original source code
logger.debug("bulkId:" + bulkId + " is TIME_RULES_VIOLATED...");
logger.debug(new StringBuilder("bulkId:").append(bulkId).append(" is TIME_RULES_VIOLATED...").toString());
// decompiled using jd-gui
logger.debug("bulkId:" + bulkId + " is TIME_RULES_VIOLATED...");
logger.debug("bulkId:" + bulkId + " is TIME_RULES_VIOLATED...");
// decompiled using cavaj
logger.debug((new StringBuilder()).append("bulkId:").append(bulkId).append(
" is TIME_RULES_VIOLATED...").toString());
logger.debug((new StringBuilder("bulkId:")).append(bulkId).append(" is TIME_RULES_VIOLATED...").toString());
Original source code consists of two log lines which prints the same thing but using different ways to see differences in decompiler behaviours.
Consider the first line: jd-gui shows it as if compiler never touches the string concatenations. On the other hand cavaj displays a StringBuilder usage. Which one is the actual one. Does jd-gui assume that all StringBuilder expressions in byte code are actually string concatenations?
Consider the second line: jd-gui displays the same string concatenation statement, while cavaj decompiles without changing the way it is formed. As a result, jd-gui’s assumption stated above holds true.
Conclusion
Java compiler really converts String concatenations into StringBuilder expressions. Since string concatenations are compiled as StringBuilder expressions, in source code using string concatenations instead of StringBuilders is preferable. Because string concatenations are more readable.
Finally in terms of reflecting actual compiled code cavaj works better.
Comments
Post a Comment