2012-02-15 89 views
2

資源使用優化有一個範例: - 儘早獲取併發布。考慮這個範例。我總是看到下面的序列DB調用:資源優化問題.net

  1. 開放連接錯誤
  2. 創建命令
  3. 做驗證
  4. 設定參數
  5. 最後執行命令

是,如果我anythng錯做?

  1. 創建命令
  2. 做驗證
  3. 設定參數
  4. 開放連接錯誤
  5. 最後執行命令

e.g

SqlCommand cmd = new SqlCommand(); 
cmd.CommandText = "cus"; 
cmd.CommandType = CommandType.StoredProcedure; 
//Configure input parameters 
SqlParameter param = new SqlParameter(); 
param = cmd.Parameters.Add(new SqlParameter("@id", 2)); 
param.Direction = ParameterDirection.Input; 
SqlConnection conn = new SqlConnection("Data Source=localhost; Integrated Security=SSPI; Initial Catalog=SpringApp;"); 
conn.Open(); 
cmd.Connection = conn; 
cmd.Prepare(); 
SqlDataReader reader = cmd.ExecuteReader(); 
+0

YOu可以編輯您的問題 – Blorgbeard 2012-02-15 17:09:50

+0

請務必關閉您的連接 – gprasant 2012-02-15 17:15:25

回答

1

是的,第二個序列更好。多少取決於1,2,3的工作量。我通常不會將CreateCommand和SetParameter視爲大問題,但驗證可能需要一些時間,甚至可能導致取消整個事情。很遺憾,如果您已經打開了連接,然後找出數據是無效的。

2

釷Ë第二種情況是去一個分辯道:

打開connection儘可能晚並儘快關閉

0

你正在做的與你說的範例完全相反。

1)打開連接錯誤是採集晚

你應該做的一切是可能的,特別是驗證,打開你的連接之前的oposite。 當其完成後,使用「使用」的語句來打開和自動關閉連接

2

是的第二序列是好的,其實如果它需要的任何時間顯著量來創建你的命令,其實是優選的,因爲它的葉子連接打開的時間更少(但通常創建命令需要的時間很少,所以這不會有明顯的差別,所以實際上你不應該在這方面大驚小怪)。

我會建議您使用盡可能以釋放資源並作出using statement更清楚你的對象的生命週期是:

using (SqlCommand cmd = new SqlCommand()) 
{ 
    cmd.CommandText = "cus"; 
    cmd.CommandType = CommandType.StoredProcedure; 
    //Configure input parameters 
    SqlParameter param = new SqlParameter(); 
    param = cmd.Parameters.Add(new SqlParameter("@id", 2)); 
    param.Direction = ParameterDirection.Input; 

    using (SqlConnection conn = new SqlConnection("Data Source=localhost; Integrated Security=SSPI; Initial Catalog=SpringApp;")) 
    { 
     conn.Open(); 
     cmd.Connection = conn; 
     cmd.Prepare(); 

     using (SqlDataReader reader = cmd.ExecuteReader()) 
     { 

     } 
    } 
} 
1

第二個版本更是一個很小的點點高效。但實際上它根本不重要。我懷疑你可以衡量它。該命令的創建不是RPC活動。一條命令只是RAM中的幾個字節。它很便宜。

但是:如果你關心資源管理,那麼不要把你的一次性物品放入使用區塊是一種死亡罪!如果發生異常,您將泄漏一個SqlConnection!

您的電話準備工作是空的(What does SqlCommand.Prepare() do and when should it be used?),可以刪除。