I am doing some work updating a data access library that our company uses to call stored procedures on an Oracle database. The library currently allows the calling application to use a single OracleCommand (IDbCommand) object and a single OracleConnection (IDBConnection) to make several calls. This means the caller would add parameters for a call, make the call, clear the parameters and repeat. When finished, the consumer application calls dispose to clean everything up.
I can make things much cleaner by using “using” statements within the library to make sure the command and connection objects are cleaned up after each call but this would mean the above functionality would be lost and a new command/connection would be created per call. I see this being done in most examples I find, but then they are usually only simple examples.
My question: Is it worthwhile to allow the command and/or the connection to persist between calls? Is it overly expensive to recreate them each time?
It is about scalability. The cost to create and dispose a command is cheap. Holding the connection open is the costly part. If you have 1000 active clients holding 1000 open connections then that is a load on the database. I often hold the connection object but just close the connection. That takes the load off the database and there is very little overhead to holding a connection object in .NET. In a typical end user program a connection is only used a small fraction of the time so closing the connections when not in use those 1000 users may only have 10 active connections. Now a programs like a data loader using a connection 1/2 the time then leave the connection open.