Many times i have come accross a situation where there is a loop and a new object is constructed at the beginning of the loop and added to a collection. For example, pseudocode:
iterating over a resultset do
create an object
set instance data in object to some resultset data
put object in collection
next
How is this approach instead?
create an object
iterating over a resultset do
set instance data in object to some resultset data
put object in collection
next
What are the pros and cons of both the approaches? Which can be faster? Is there a better way than the two?
P.S. : i dont know what tags to put. Pardon me.
Depending on the language you are using to implement that you will get different results.
Some languages return a reference to an object. So the first option will do what you expect because a new object is created and appended to the collection with its own values.
But if the language simply returns a reference to an object and you try and do the second method
So after iterating the resultset you will end up with a bunch of references to the same object in your collection, with the values being whatever was last assigned to.