My class contains few properties which never used anywhere (This is a DEMO of my real scenario). I heard that JVM optimized our Java code.
Does JVM / Compiler optimize / remove unused properties of an object?
public class A {
private int unused1 = 100;// never called anywhere inside object
public int unused2 = 999;// never called anywhere in the application
}
I know that I need to study hard about JVM, Compiler and optimization. But the answer needed because within a short period I have to decide whether I will delete all(as much as possible) unused variable manually from a large codebase(about 10,000 java files) or just depend on JVM optimization.
Expecting some interesting and fruitful suggestions.
TL;DR: No, the JVM compiler (javac) will not optimise out unused variables.
Let's have a look at the bytecode the javac compiler produces.
Using this as a test class:
public class Test {
private int test = 5;
private int test2 = 10;
private String aString = "HelloWorld";
}
Produces:
Classfile /C:/Users/Huw/Desktop/Test.class
Last modified 19-Apr-2016; size 331 bytes
MD5 checksum 1c49b13d1d5d8a2c52924b20753122af
Compiled from "Test.java"
public class Test
minor version: 0
major version: 52
flags: ACC_PUBLIC, ACC_SUPER
Constant pool:
#1 = Methodref #7.#19 // java/lang/Object."<init>":()V
#2 = Fieldref #6.#20 // Test.test:I
#3 = Fieldref #6.#21 // Test.test2:I
#4 = String #22 // HelloWorld
#5 = Fieldref #6.#23 // Test.aString:Ljava/lang/String;
#6 = Class #24 // Test
#7 = Class #25 // java/lang/Object
#8 = Utf8 test
#9 = Utf8 I
#10 = Utf8 test2
#11 = Utf8 aString
#12 = Utf8 Ljava/lang/String;
#13 = Utf8 <init>
#14 = Utf8 ()V
#15 = Utf8 Code
#16 = Utf8 LineNumberTable
#17 = Utf8 SourceFile
#18 = Utf8 Test.java
#19 = NameAndType #13:#14 // "<init>":()V
#20 = NameAndType #8:#9 // test:I
#21 = NameAndType #10:#9 // test2:I
#22 = Utf8 HelloWorld
#23 = NameAndType #11:#12 // aString:Ljava/lang/String;
#24 = Utf8 Test
#25 = Utf8 java/lang/Object
{
public Test();
descriptor: ()V
flags: ACC_PUBLIC
Code:
stack=2, locals=1, args_size=1
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: aload_0
5: iconst_5
6: putfield #2 // Field test:I
9: aload_0
10: bipush 10
12: putfield #3 // Field test2:I
15: aload_0
16: ldc #4 // String HelloWorld
18: putfield #5 // Field aString:Ljava/lang/String;
21: return
LineNumberTable:
line 1: 0
line 3: 4
line 4: 9
line 5: 15
}
SourceFile: "Test.java"
As you can see, the compiler still allocates the field properties.
So no, unused variables will still be allocated pointers (for Objects) and memory (for primitives).
No unfortunately their is no such magic hopefully, you have no other choice but to clean up your code using tools like PMD
or FindBugs
that will help you to detect such kind of issues and many more.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With