非单例 sql 连接的性能更好吗?

Is the performance of non singleton sql connections better?

这是以下问题的后续问题:Is it necessary to deconstruct singleton sql connections?

正如那里的一些评论所说,将单例用于 sql 连接而不是多次使用是糟糕的设计。

但令我感兴趣的是一种说法,即 using 变体的性能比单例变体更好。现在正如我所说的那样,我很清楚这是一个糟糕的设计(我知道那里单身人士的大多数优点和缺点......尤其是缺点)。令我惊讶的是性能声明。

通常我会想:好的,在一个程序中打开和关闭 sql 连接 100-1000 次 运行 应该比只这样做一次性能低。因此我的问题是:非单例变体的性能真的更好吗?如果是的话,为什么?

单例:

public class SimpleClass
{
    // Static variable that must be initialized at run time. 
    public static SqlConnection singletonConnection;

    // Static constructor is called at most one time, before any 
    // instance constructor is invoked or member is accessed. 
    static SimpleClass()
    {
        singletonConnection = new SqlConnection("Data Source.....");
    }
}

使用示例:

using (SqlConnection connection = new SqlConnection("Data ...")) 
{
  ....
}

基本上答案很简单:

Connecting to a database server typically consists of several time-consuming steps. A physical channel such as a socket or a named pipe must be established, the initial handshake with the server must occur, the connection string information must be parsed, the connection must be authenticated by the server, checks must be run for enlisting in the current transaction, and so on. In practice, most applications use only one or a few different configurations for connections.

This means that during application execution, many identical connections will be repeatedly opened and closed. To minimize the cost of opening connections, ADO.NET uses an optimization technique called connection pooling.

您不应该将单例用作某种 'performance accelerator',因为它不是它的用途。通过使用它来存储一个静态 SQL 连接,您将面临许多内存和连接问题。你应该如何关闭连接?你应该如何释放消耗的内存?当一个连接关闭时,您将为所有应用程序用户关闭它。您打算如何重新连接该方法?

“连接池”的基本意思是,即使您正在创建许多 SqlConnection 个对象,只要它们与连接字符串没有区别,就可以重用现有连接。

可以找到一些详细信息there