班级链接:

https://developer.huawei.com/consumer/cn/training/classDetail/46b54a56c7e54e74973e0af43c077bff?type=1?ha_source=hmosclass&ha_sourceId=89000248

1. 核心内容

Preferences是鸿蒙轻量级键值对存储方案,适合存储用户偏好设置(如主题、音量),但大量频繁读写易导致性能问题。优化核心在于减少IO操作,通过批量读写、缓存常用数据、合理设置flush时机实现。实际开发中,建议封装单例工具类管理Preferences实例,避免重复初始化,同时对高频读取数据进行内存缓存,批量更新时统一flush。API 20新增批量存储接口,可大幅提升多键值写入效率。

2. 代码示例 

typescript
import dataPreferences from '@ohos.data.preferences';

class PrefsOptimizedUtil {
  private static instance: PrefsOptimizedUtil;
  private prefs: dataPreferences.Preferences | null = null;
  private cache: Record<string, any> = {}; // 内存缓存常用数据

  private constructor() {}

  // 单例初始化,避免重复创建
  public static async getInstance(context: any): Promise<PrefsOptimizedUtil> {
    if (!this.instance) {
      this.instance = new PrefsOptimizedUtil();
      this.instance.prefs = await dataPreferences.getPreferences(context, "app_config");
      // 初始化缓存常用数据
      await this.instance.initCache();
    }
    return this.instance;
  }

  // 初始化缓存
  private async initCache() {
    const keys = ["theme_mode", "music_volume", "login_status"];
    const batchData = await this.prefs?.getBatch(keys); // API 20批量读取
    if (batchData) this.cache = batchData;
  }

  // 读取数据(优先从缓存获取)
  public getData<T>(key: string, defaultValue: T): T {
    return this.cache[key] ?? defaultValue;
  }

  // 批量写入数据,统一flush
  public async batchPutData(data: Record<string, any>) {
    if (!this.prefs) return;
    Object.keys(data).forEach(key => this.cache[key] = data[key]);
    await this.prefs.putBatch(data); // API 20批量写入
    await this.prefs.flush(); // 统一持久化
  }
}

3. 总结

Preferences优化的关键是减少磁盘IO操作,通过单例模式避免实例重复创建,内存缓存减少读取开销,批量接口提升写入效率。适合数据量小、读写频繁的配置场景,不建议存储复杂对象或大量数据。实际开发中,结合API 20的新特性,能进一步提升性能,同时需注意缓存与磁盘数据的一致性,避免数据同步问题。

4. 注意事项

1. 单例初始化需在应用启动时完成,避免在组件中重复调用;

2. 缓存数据需及时更新,避免缓存与磁盘数据不一致;

3. 批量写入后必须调用flush,否则数据可能丢失;

4. 避免存储超过1MB的数据,建议按业务拆分多个Preferences文件;

5. 敏感数据需加密后存储,不建议直接存储密码等信息。

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐