2013-02-17 197 views
0

我有一張包含大約5億條記錄的表格。我正在讀取表格中的數據並將它們存儲在Dictionary中。從數據庫中讀取海量數據的最快方法

編輯:我將數據裝入字典,因爲這些數據需要與數據從索引服務器未來的另一個捲進行比較。

我的代碼如下:

public static void GetDetailsFromDB() 
{ 
    string sqlStr = "SELECT ID, Name ,Age, email ,DOB ,Address ,Affiliation ,Interest ,Homepage FROM Author WITH (NOLOCK) ORDER BY ID"; 
    SqlCommand cmd = new SqlCommand(sqlStr, _con); 
    cmd.CommandTimeout = 0; 

    using (SqlDataReader reader = cmd.ExecuteReader()) 
    { 
     while (reader.Read()) 
     { 
      //Author Class 
      Author author = new Author(); 

      author.id = Convert.ToInt32(reader["ID"].ToString()); 
      author.Name = reader["Name"].ToString().Trim(); 
      author.age = Convert.ToInt32(reader["Age"].ToString()); 
      author.email = reader["email"].ToString().Trim(); 
      author.DOB = reader["DOB"].ToString().Trim(); 
      author.Address = reader["Address"].ToString().Trim(); 
      author.Affiliation = reader["Affiliation"].ToString().Trim(); 
      author.Homepage = reader["Homepage"].ToString().Trim(); 

      string interests = reader["Interest"].ToString().Trim(); 
      author.interest = interests.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).Select(p => p.Trim()).ToList(); 

      if (!AuthorDict.ContainsKey(author.id)) 
      { 
       AuthorDict.Add(author.id, author); 
      } 

      if (AuthorDict.Count % 1000000 == 0) 
      { 
       Console.WriteLine("{0}M author loaded.", AuthorDict.Count/1000000); 
      } 
     } 
    } 
} 

這個過程是需要長時間閱讀,所有500萬條記錄的數據庫存儲。另外,RAM的使用率非常高。

可以這樣進行優化?還可以減少運行時間嗎?任何幫助表示讚賞。

+3

你爲什麼要裝500M記錄RAM? – Mat 2013-02-17 14:23:36

+0

我需要將記錄與其他一些數據進行比較。 – SKJ 2013-02-17 14:24:31

+8

那麼?你有一個數據庫,那些擅長搜索數據。如果您想獲得相關答案,請詳細說明您要實現的目標。 – Mat 2013-02-17 14:25:51

回答

3

如果我認爲我的鼻子,我可以想出以下的優化:

  1. 商店序中的局部變量的字段的位置和參考使用這些有序變量在reader領域。

  2. 不要呼籲讀者ToString和轉換 - 剛剛得到的值出正確的類型。

  3. 檢查在AuthorDict作者id的存在,只要你有ID。如果你不需要它,甚至不要創建Author實例。

    using (SqlDataReader reader = cmd.ExecuteReader()) 
    { 
        var idOrdinal = reader.GetOrdinal("ID"); 
        //extract other ordinal positions and store here 
    
        while (reader.Read()) 
        { 
         var id = reader.GetInt32(idOrdinal); 
    
         if (!AuthorDict.ContainsKey(id)) 
         { 
          Author author = new Author(); 
          author.id = reader.GetInt32(idOrdinal); 
          ... 
         } 
        } 
    }