Skip to main content
 首页 » 编程设计

c#之为什么 ExecuteScalar 第一次调用需要时间

2024年02月05日15arxive

下面是我的程序,用于测量 ExecuteScalar 进行多次迭代所花费的时间。

static void Main(string[] args) 
{ 
    string sqlConnectionString = "Data Source=.\\SQLEXPRESS;Initial Catalog=Test;Integrated Security=True"; 
    SqlConnection connection = new SqlConnection(sqlConnectionString); 
    for(int i=0; i <4; i++){ 
        Stopwatch stopWatch = new Stopwatch(); 
 
        string sqlCommand = "Insert into TestTable (SNO, Name) values (" + i + ",' " + i + "')"; 
        SqlCommand command = new SqlCommand(sqlCommand, connection); 
        connection.Open(); 
        stopWatch.Start(); 
        var result = command.ExecuteScalar(); 
        stopWatch.Stop(); 
        connection.Close(); 
        Console.WriteLine("Time elapsed to insert row " + i + " : " + stopWatch.ElapsedMilliseconds); 
    } 
    Console.ReadKey(); 
} 

输出:

Time elapsed to insert row 0 : 3 
Time elapsed to insert row 1 : 1 
Time elapsed to insert row 2 : 0 
Time elapsed to insert row 3 : 0 

我的问题是为什么第一次迭代需要 3 毫秒,而剩下的时间比这要短。

提前致谢。

请您参考如下方法:

这是由于连接池。建立连接后(无论您是否关闭它),只要您的连接字符串保持不变,连接就会被合并,从而导致更快的连续执行。