November 20, 2013

Where to declare Java Variables?

Recently I went to Java Meetup. And it was all about Garbage Collector. So I learned lot more about Garbage Collectors. So Dr. Daya's suggestions was not to declare variable in higher scopes unless we really know what we do. For a example, don't declare class level variables if we are only using it inside on method. Then I was thinking about doing some tests on variable declarations. I used following code:

Then I used following code to do see the difference. Following code is declaring a variable in a higher scope(which is bad according to Dr.Daya).

First Code execution time was 1756557171 ms.(
Second Code execution time was 1826556296 ms.(

With those statistics, it's clear that declaring objects(Strings) in relevant scopes improves performance. But primitive data types are different. So I did same code for a primitive data type.

int is a primitive data type. It will not behave like String did. Improvement is upside down here.

Third Code execution time was 1829664932 ms.(
Forth Code execution time was 1681147372 ms.(

Those statistics were collected from same machine with same condition. And I ran those programs against JRE 1.6.0_45. I saw a difference in result, when I ran those programs on JRE 1.7.0_45. Now I'm digging into it!

No comments:

Post a Comment