KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
Here's my test code, which seems to suggest that it's better to connect multiple times instead of connecting just once. Am I doing something wrong? int numIts = 100; Stopwatch sw = new Stopwatch(); sw.Start(); using (SqlConnection connection = new SqlConnection(connectionParameters)) { connection.Open(); for(int i = 0; i < numIts; i++) { SqlCommand command = new SqlCommand(sqlCommandName, connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue(par1Name, par1Val); command.Parameters.AddWithValue(par2Name, par2Val); using(SqlDataReader reader = command.ExecuteReader()) { } } } sw.Stop(); TimeSpan durationOfOneConnectionManyCommands = sw.Elapsed; Console.WriteLine(durationOfOneConnectionManyCommands); sw.Reset(); sw.Start(); for(int i = 0; i < numIts; i++) { using (SqlConnection connection = new SqlConnection(connectionParameters)) { connection.Open(); SqlCommand command = new SqlCommand(sqlCommandName, connection); command.CommandType = CommandType.StoredProcedure; command.Parameters.AddWithValue(par1Name, par1Val); command.Parameters.AddWithValue(par2Name, par2Val); using(SqlDataReader reader = command.ExecuteReader()) { } } } sw.Stop(); TimeSpan durationOfManyConnections = sw.Elapsed; Console.WriteLine(durationOfManyConnections); Output: //output: //00:00:24.3898218 // only one connection established //00:00:23.4585797 // many connections established. // //output after varying parameters (expected much shorter): //00:00:03.8995448 //00:00:03.4539567 Update: OK, so those who said it would be faster w/ one connection have it. (although the difference is marginal, if any.
Tags (comma-separated)
Save Edits
Cancel