January 18, 2021
Hot Topics:

Want to Optimize Your Java Code? Shrink the Bytecode

  • By Raghu Donepudi
  • Send Email »
  • More Articles »

Software development is much like the game of Whac-a-Mole for programmers. Most of their time is spent addressing requirement changes and their implications. As a result, many lines of code get either commented out or go unused. With deadlines constantly looming, hardly any time is set aside for cleaning up or optimizing the code.

This is where a simple command-line tool called ProGuard comes in. ProGuard is an open-source Java class file shrinker, optimizer, obfuscator, and pre-verifier. Using simple command-line options, you can identify all the dead code and optimize all your code, including third-party JAR files. You can clean up compiled code right after it compiles or clean up the compiled JAR files before deployment. The result is smaller, more compact code archives.

As several commercial Java obfuscators are available, this article focuses on the shrink functionality offered by ProGuard. It shows how to use ProGuard to find all the dead code in your codebase and then shrink the JAR files.

Code Shrinking and Optimization

Code shrinking reduces the size of Java class files when your application does not use all of the bytecode. The shrinking engine analyzes the bytecode to find the code that cannot be reached from a set of given code entry points. The removal of these obsolete code fragments (either entire classes or single methods and fields) is called code shrinking. Shrinking involves other tasks such as making subroutines inline as well. If your application uses well-designed third-party tools, the shrinking engine will remove all other functionalities except the ones used by your application—without compromising any functionality.

However, you need to be careful when shrinking third-party tools as it might violate the support license requirements. ProGuard provides a keep option to prevent the shrinking engine from shrinking the code specified with this option. You can specify class names or method names with this option as well. Make sure to use the keep option for any code that you intend to share with other applications in the future.

The code optimization process identifies and removes calls to methods that are either user written or calls to system methods, if it finds that the return values are not used. ProGuard analyzes the entire hierarchy of each method automatically before removing it. Code optimization is a complex process that requires expert analysis. Use this option with care.

Page 1 of 2

This article was originally published on December 2, 2009

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date