Home > Back-end >  How to remove the unused constants from the generated Java class file
How to remove the unused constants from the generated Java class file

Time:08-01

I often use constants in my Java programs, however when taking a look at a decompiled Java class file, I noticed that all the constant's uses throughout the program was replaced by their literal values, while the original declarations and assignments at the top of the class was still present, I'm wondering if these variables are just sitting there wasting memory since they're not being used anywhere in the file. and if there's a way to restrict constants only to compile time and have them removed after the class file is generated.

CodePudding user response:

The compiler is smart enough to use memory efficiently in this kind of case. And, even let's suppose that you did have wasted memory per constant, let's do a thought experiment on how much 'space' that may be, realistically.

Let's say we had a mixture of string, int, and other basic types. Each char in a string is 2 bytes in java, and an int is 4 bytes. Let's say we had 75,000 char constants and 25,000 int constants. That is 75k * 2 so 150k bytes or ~150 kilobytes of memory for the string constants For the ints that is 25k * 4 or 100k, so ~100 kilobyte of memory.

So a total of ~250kb.

The most basic computer you can buy these days has a minimum of 4gb of ram, more likely 8gb to 16gb.

So 250kb / 4000000kb * 100 = 0.00625% of the lowest spec modern computer.

Now if you are running some microcontroller or other limited hardware, it maaay be something, but even then it is doubtful and you probably aren't using java.

As a general rule of thumb, compilers and interpreters tend to be pretty good at their job, and trusting them to do the right thing most of the time, for most programmers and programs is good enough.

There are times when certain patterns, such as massive creation of new objects, then triggering garbage collection or other issues like that can have large performance impacts.

The key is to know where actual bottlenecks and gotchya's are within a language/computer/use patterns.

It does get more complicated once we move into the distributed space and massive scale - but again unless you are working in that kind of environment, you generally don't need to consider it.

Focus your expectations on your use case, and if you are optimizing for a 10 millisecond gain for something only a few people use, it's probably a waste of time - unless you are doing it for fun.

  •  Tags:  
  • java
  • Related