Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Performance comparison w.r.t memory on Loop variables

 
Muhammad Yasir Ch
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I like to know the performance comparison w.r.t memory between following code snippets. According to my knowledge the first code snippet will consume more memory as compared to second one.

Code1
for (long l = 0; l <= 1000000; l++) {
ArrayList<myBean> arrBeanList = getBeanList();
}

Code2
ArrayList<myBean> arrBeanList = null;
for (long l = 0; l <= 1000000; l++) {
arrBeanList = getBeanList();
}
 
Ankit Garg
Sheriff
Posts: 9528
32
Android Google Web Toolkit Hibernate IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The answer cannot be straight forward IMO. Code 1 creates more reference variables (arrBeanList) but they also become unreachable after each iteration. Thus the object returned by getBeanList() will be eligible after each iteration. Code 2 reuses the same reference variable arrBeanList but after the last iteration the object returned by getBeanList() will not be directly eligible for GC (if there is more code to follow)...
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic