java


pojo declaraion outside forloop


I have an one scenario in my application,
I have to add 20 POJO objects into ArrayList. In that case I have a method like below.
public void methodname() {
ArrayList arr = new ArrayList();
for(int i=0;i<20;i++) {
User userobj = new User();
userobj.setName("xxx");
userobj.setFirstName("xxx");
userobj.setLastName("yyy");
arr.add(userobj);
} // end of for loop
}
one of friends suggest to change the UserObj declaration outside for loop.
public void methodname() {
User userobj = new User();
ArrayList arr = new ArrayList();
for(int i=0;i<20;i++) {
userobj.setName("xxx");
userobj.setFirstName("xxx");
userobj.setLastName("yyy");
arr.add(userobj);
} // end of for loop
}
in the first approach, I created the userobj inside the for loop, so when next iteration comes previous userobj will be eligible for garbage collector..
I would like to know is there any significant performance will improve on the second approach?
I would like to know is there any significant performance will improve on the second approach?
Did you experience a difference?
When programming you should focus on correctness and readability of your code.
Do not even Think about performance unless you have an actual performance problem and you have proven by profiling that a certain construct is the cause.
The ultimate universal performance tip is:
The fastest way to do something is not doing it.
So focus on good algorithms that avoid unneeded/hidden loops rather than on syntax variants that may improve performance.
The main difference between the first and the second approach is that in the first case you create 20 different User in memory which are assigned to the array.
In the second case you create only one User in memory but change its properties 20 times and assign the same User to all 20 positions of the array.
Regardless of the first scenario or the second, your User instances created are eligible for garbage collection only when the array itself is eligible for garbage collection, expect you remove the association with the array.
Garbage collection takes place only for an instance if there is no other instance referencing it.
Both the ways, will produce different results.
In the First one, you create 20 separate Objects, and add them to the List. Thus, changes on one of them, won't affect the others.
The Second, however, has the same object. Thus, changes on one will reflect the others. Actually, at the end, the attributes of the all the Objects would be the same, i.e, equal to the last added Object
Performance-wise, you can't say. The Objects would only be eligible for garbage collection, when there are no references pointing to them. However, as both the ways perform separate functions, you can't compare them.
Alas, your Friend is wrong. The First way is what you're looking for.
It needs to be inside the loop, otherwise you are only adding the SAME user 20 times !
On the second approach you will have only one last object in the list
I think that the right way is:
- declaration outside
- instantiation inside
public void methodname() {
ArrayList arr = new ArrayList();
User userobj;
for(int i=0;i<20;i++) {
userobj = new User();
userobj.setName("xxx");
userobj.setFirstName("xxx");
userobj.setLastName("yyy");
arr.add(userobj);
} // end of for loop
}

Related Links

Why does JavaFX PieChart label not show after after adding Events to each pie slice? (Java 8)
Deleting Arraylist Items by Index?
Not sure how to fix “argument lists differ in length” [duplicate]
Why IDEA warningme about unchekd cast to generic type in this line (T) this.object[position] ? But everesing is work
Selenium Marionette new connections will no longer be accepted
Play Framework: DB Connection Pool Shut Down
Resizing a frame when clicking a button
java.awt.Choice.select(Choice.java:430)
How do I get low-level storage info with Java?
Android - Checking Permissions in a Separate Class
how to implement a semantic search approach with elaticsearch
Java CSON parser?
Spinners - get item selected from array
Titan gremlin console and java returns different result for group().by() query
Foreach using 2 arraylist [on hold]
Can not size a List in JPanel

Categories

HOME
xamarin
magnific-popup
plot
layout
hashmap
relayjs
electron
objectgears
spring-jdbc
multiple-records
synchronization
slurm
elasticsearch-hadoop
reveal.js
dosgi
openrefine
highlight.js
invantive-sql
reactcsstransitiongroup
code-review
firefox-webextensions
karma-jasmine
swiftlint
paging
cx-freeze
wkwebview
kvc
claims-based-identity
lcd
xpages-ssjs
javacv
bootstrap-material-design
fluentvalidation
wtx
jspm
facebook-apps
kendo-datasource
bpel
bluestacks
exuberant-ctags
fusionpbx
io-redirection
automake
hockeyapp
neuroscience
tasker
sas-visual-analytics
arena-simulation
total-commander
filepicker
idisposable
jxcore
carrot
media-player
capacity
yt-project
wdf
angular-cache
trash
skobbler-maps
transmitfile
paypal-express
rhino-servicebus
revolution-r
historian
unity-networking
spim
xna-4.0
ora-00900
cyclomatic-complexity
embedded-code
service-accounts
mono-embedding
sailfish-os
generic-programming
clipperlib
dereference
lustre
typekit
tt-news
client-side-templating
funcunit
android-2.2-froyo
transcoding
app42
intentservice
tidy
jmapviewer
dotnetnuke-5
jelly
tinn-r
hamiltonian-cycle
broken-links
cufon
mercurial-server
subgurim-maps
tomcat-valve
appender
inotifycollectionchanged
imac
web-application-design
sproutcore-2
compiler-specific
libs
avatar
spec#
w3wp
dbisam
wsdl.exe
ajax-forms

Resources

Database Users
RDBMS discuss
Database Dev&Adm
javascript
java
csharp
php
android
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App