boltup_im_coding
boltup_im_coding

Reputation: 6665

Does Eclipse compile out unused local variables?

Consider the following code:

 public String foo(){
      String bar = doStuff();
      return bar;
 }

And then later:

 public void test(){
      doSomeLogicHere();
      String result = foo();
 }

Note that in test I get a String named result at the end of the function. Eclipse knows this is an unused variable, as it warns about it. What I'm wondering is, do these Strings get compiled out as if the call was just foo() without saving the returned String? If I commented out String result = when I'm not using it would I reduce memory consumption or does it not matter since the String is still generated and returned in foo()?

I have some debugging logic in an application I'm writing like this, and I'm wondering if it's worth it to comment out all of the Strings for a release/when I'm not using them.

Upvotes: 5

Views: 1009

Answers (2)

mikera
mikera

Reputation: 106391

The result assignment won't make any difference performance wise: the Java JIT in the JVM will optimise away these unused variables in nearly all cases.

I personally fix these kind of things just to keep my code clean and warning-free.

Upvotes: 1

TtT23
TtT23

Reputation: 7030

As far as I'm aware, compiler doesn't automatically remove unused variables. That's usually the job for optimizers/obfuscators.

For instance, in Android ProGuard removes all unused variables when you build your android app in release mode.

Upvotes: 1

Related Questions