2016-12-03 24 views
0

我在while循環中使用遊標在我的數據庫上執行多個查詢,所以每次Content Resolver返回新的遊標對象實例。我不確定有道循環的每次迭代過程中,我應該重新使用遊標:光標變量重用

  1. 關閉一次,在每次迭代結束執行

    Cursor c; 
    try { 
        while(condition) { 
         c = Context.getContentResolver().query(...); 
         // fetching values 
        } 
    } finally { 
        if (c != null) { 
         c.close() 
        } 
    } 
    
  2. 關閉其所有操作之後,

    Cursor c; 
    try { 
        while(condition) { 
         c = Context.getContentResolver().query(...); 
         // fetching values 
         if (c != null) { 
          c.close() 
         } 
        } 
    } finally { 
        if (c != null) { 
         c.close() 
        } 
    } 
    
  3. 內創建新的遊標變量while循環

    while(condition) { 
        Cursor c = Context.getContentResolver().query(...); 
        try { 
         // fetching values 
        } finally { 
         if (c != null) { 
          c.close() 
         } 
        } 
    } 
    

回答

1
  • 由於您在循環中分配了一個新的遊標,並且只關閉了最後一次分配的遊標,因此情況1很糟糕。

  • 情況2和3非常相似,但我更喜歡情況3,因爲情況2可以意外地突破環路,但情況3將光標保留在環路範圍內並且環路可以繼續運行。

+0

而且看起來最乾淨以及imo。 – tomwyr

1

在您的示例中,第三個變體是最有用的,因爲您在每個循環中打開關閉相同的Cursor對象。你什麼也沒有損失:沒有內存泄漏沒有應用程序+數據庫崩潰。

+0

我想了一會兒,在循環中聲明變量時性能有所不同,但沒有更多。 – tomwyr

+0

@tomwyr,當然,在每次迭代中,您的代碼會生成新變量。但你真的需要它。否則,它不會工作:) – Vyacheslav