*Conn vs *DB performance difference


Based on my findings, the *Conn methods are more performant (average 30%) than the *DB methods although they are used to achieve same result. What I am trying to understand is, if *Conn is more performant than *DB why would the doc read as shown below?


Conn represents a single database connection rather than a pool of database connections. Prefer running queries from DB unless there is a specific need for a continuous single database connection.

Hi, @GoingToGo,

Can you provide the code and results of those findings? As the documentation you quoted says, *DB represents a pool of connections whereas *Conn represents a single connection. If your use case involves a single goroutine, I suspect a *Conn will have slightly better performance than a *DB because the *DB has to delegate its queries and statements to *Conns in its pool and then return the *Conns back to the pool, so there’s additional overhead. If your use case involves use of the database concurrently, I suspect sharing one *Conn object between multiple goroutines will result in worse performance than sharing the *DB (assuming *Conns are safe for concurrent use; I skimmed through the database/sql package’s documentation and though I see that *DBs are recommended for concurrent use, I also see that *Conns can have statements prepared and be Closed concurrently. :man_shrugging:)

If your benchmark doesn’t require IO on the database server (e.g. your query is SELECT GETDATE(); or SELECT 1+2;), I would not be surprised if the *DB overhead is more than that of the *Conn, but if you are selecting rows from a table and seeing a 30% performance difference between *DB and *Conn, I am very interested to learn what your test(s) and architecture look like.


Hi @skillian

You are right! Running multiple goroutines changes the whole story. *Conn is definitely not for such scenarios. I think the best bet for the most cases is to stick with *DB and we worry less.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.