I am trying to get data from db and present that data in json object. to represent the data into json object i'm trying to iterate from resultset object and add result into a list. But is it good to create a class object inside while loop. In my case it is going to create more than 100 objects.
Emp emp;
List<Emp> empList = new ArrayList<Emp>();
while(rs.next()){
emp = new Emp();
emp.setEMPLOYEE_ID(rs.getString("EMPLOYEE_ID"));
emp.setFIRST_NAME(rs.getString("FIRST_NAME"));
emp.setLAST_NAME(rs.getString("LAST_NAME"));
empList.add(emp);
}
System.out.println(empList.size());
ObjectWriter ob = new ObjectMapper().writer().withDefaultPrettyPrinter();
json = ob.writeValueAsString(empList);
It is usually better to create the object inside the loop. Java optimizes memory usage for short-lived objects. Memory allocation time for an object is next to zero, and collection time is zero, other than the overhead of running a minor GC at all. GC time in minor collections is proportional to the number of live objects, so the more objects that die, the faster the collection. This also keeps them out of the tenured generation, which takes longer to clean up. So not only is it "fine" to create the object inside the loop, but you should do so, and indeed should declare it inside the loop. In your code example, emp
has too wide a scope. You can also use the empty diamond operator, <>
, as the generifier for ArrayList
in the declaration of empList
(which should not have the word List
in its name, but be a plural like employees
).