I am using lambdas for ensuring closing of the result set and database connection.
In my below code I am capturing variables like (activeList, inActiveList, user). In many places it was told, although linkage(one time cost) and invocation cost are similar for capturing and non-capturing lambdas, capturing lambdas are not performant, due to the intermediate "capture cost". At each invocation lambda object needs to be created. For non-capturing lambda it is one time, then subsequent calls will reuse the same object. But for capturing lambda each time object has to be created.
I have added my code snippet below. This type of capturing lambdas comes more often in my web-application code. My assumption is since number of select query, executed for each request is relatively low, using this type of capturing lambdas would not make considerable performance impact. Is it correct, or I am doing wrong.
User user = getUser(id);
List<Integer> activeList = new ArrayList<>();
List<Integer> inActiveList = new ArrayList<>();
HashMap<String, Object> h = new HashMap<>();
DBUtil.execute(sqlQuery (rs) -> {
String id = rs.getString("id");
h.put("id", id)
h.put("name", rs.getString("name"));
if(user.isAdmin()){
h.put("pay", re.getInt("pay"))
}
int status = rs.getInt("status");
if(status == 1){
activeList.add(id);
} else if(status == 2){
inActiveList.add(id);
}
})
static void execute(String sql, Consumer<ResultSet> iteratorFn) {
try {
Connection conn = getConn();
Statement stmt = conn.createStatement(sql)
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
iteratorFn.accept(rs);
}
rs.close();
} finally {
if(stmt != null){
stmt.close()
}
if(conn != null){
conn.close()
}
}
}
Reference
https://ionutbalosin.com/2018/12/passing-thismethod-reference-within-a-loop-affects-performance/
https://www.infoq.com/articles/Java-8-Lambdas-A-Peek-Under-the-Hood/