Felix
Felix

Reputation: 203

Performance hit by using Spring jdbcTemplate compared to plain PreparedStatement

i am just benchmarking a complex system and found that queries going through Spring are really slow.

It adds ~600ms.

The benchmark code compares the following:

case TEMPLATE:
{
    t = System.currentTimeMillis();
    jdbcTemplate.update(getUnnamedPreparedStatement(query), new PreparedStatementSetter() {

        @Override
        public void setValues(PreparedStatement ps) throws SQLException {
            int i = 1;
            for (Object o : queryParameters) {
                ps.setObject(i++, o);
            }
        }
    });
    break;
}

case PREPAREDSTATEMENT:
{
    Connection c = dataSource.getConnection();
    t = System.currentTimeMillis();
    PreparedStatement ps = c.prepareStatement(getUnnamedPreparedStatement(query));
    int index = 1;
    for (Object parameter: queryParameters) {
        ps.setObject(index++, parameter);
    }
    ResultSet rs = ps.executeQuery();
    rs.next();
    break;
}

Both queries give the same result and the order does not matter. Moreover, it does not depend on the query type (i.e. SELECT, UPDATE).

I have run the test a dozen times and the results are stable.

What does the Spring jdbcTemplate do, that the PreparedStatement does not do?

Upvotes: 2

Views: 3144

Answers (2)

tom
tom

Reputation: 2745

Since my comment above seems to be the correct answer I'll post it as an answer for future consulting.

@Felix, reusing connections has nothing to do with spring but with your connection pool if you have it. So that should be taken into account.

So basicly I think the connection pool was missing in the spring project.

Upvotes: 2

JB Nizet
JB Nizet

Reputation: 691735

Your first case executes an update query, whereas the second one executes a select query. The second one should use ps.executeUpdate() to be similar to the first one.

Upvotes: 0

Related Questions