Read speed of SharedPreferences

前端 未结 4 1684
庸人自扰
庸人自扰 2020-12-09 15:06

How fast are SharedPreferences? Is there a way to put them in memory for reading? I have a small amount of data that a ListView has to query to d

相关标签:
4条回答
  • 2020-12-09 15:43

    Is there a way to put them in memory for reading?

    They are in memory, after the first reference. The first time you retrieve a specific SharedPreferences (e.g., PreferenceManager.getDefaultSharedPreferences()), the data is loaded from disk, and kept around.

    0 讨论(0)
  • 2020-12-09 15:50

    I have a small amount of data that a ListView has to query to display each cell

    Can't you make a Singleton, a common class and read it from there from second time? I would do that.

    0 讨论(0)
  • 2020-12-09 15:53

    My advice is to test your performance first, and then start worrying about speed. In general, you'll be happier with an app that prioritizes maintainability as well as speed. When engineers start out to achieve performance before they get the app stable, the result is an app that runs a bit faster but has lots of bugs.

    0 讨论(0)
  • 2020-12-09 15:56

    According to this link, getSharedPreferences is not that much heavy because it opens file only when you call getSharedPreferences first time:

    // There are 1000 String values in preferences
    
    SharedPreferences first = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
    // call time = 4 milliseconds
    
    SharedPreferences second = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
    // call time = 0 milliseconds
    
    SharedPreferences third = context.getSharedPreferences("com.example.app", Context.MODE_PRIVATE);
    // call time = 0 milliseconds
    

    But using get methods will take some time for the first time you call it:

    first.getString("key", null)
    // call time = 147 milliseconds
    
    first.getString("key", null)
    // call time = 0 milliseconds
    
    second.getString("key", null)
    // call time = 0 milliseconds
    
    third.getString("key", null)
    // call time = 0 milliseconds 
    
    0 讨论(0)
提交回复
热议问题