liangjingkanji / Net

Android 基于协程/OkHttp网络请求工具
http://liangjingkanji.github.io/Net/
MIT License
1.87k stars 211 forks source link

读取缓存耗时 #139

Closed tanranran closed 1 year ago

tanranran commented 1 year ago

问题描述

读取缓存耗时,华为mate10 机器,大约180ms

期望行为

读取缓存耗时控制在50ms之内

如何复现

var starTime = System.currentTimeMillis()
scopeNetLife {
    Log.d("日志", "scopeNetLife耗时" + (System.currentTimeMillis() - starTime))
    starTime = System.currentTimeMillis()
    Get<String>(Api.BANNER) {
        setCacheKey(Api.BANNER)
        setCacheMode(CacheMode.READ)
    }.await().toString()
    Log.d("日志", "读取缓存耗时" + (System.currentTimeMillis() - starTime))
}

截图

image

版本

liangjingkanji commented 1 year ago
  1. Net采用的缓存机制是DiskLruCache, 这是OkHttp使用Okio实现的缓存机制, OKio已经是业界速度公认效率最高之一(比java.io/java.nio), 且Net所有IO相关操作全部使用的OKio

  2. scopeNetLife使用的协程调度器切换, 这个在Net中我认为没有进一步优化空间

首先第一次执行scope()/IO读写都会构建线程池等初始化相对较慢, 缓存读写速度和设备性能/缓存大小有关, 你的华为Mate10速度慢很正常, 不仅是设备老久还CPU性能低下

以下是我运行结果

第一次

12:40:08.010  D  scopeNetLife耗时13
12:40:08.155  D  读取缓存耗时145
12:40:11.843  D  scopeNetLife耗时5
12:40:11.860  D  读取缓存耗时17
12:40:15.422  D  scopeNetLife耗时6
12:40:15.437  D  读取缓存耗时15
12:40:17.835  D  scopeNetLife耗时6
12:40:17.859  D  读取缓存耗时24

第二次

12:40:48.156  D  scopeNetLife耗时29
12:40:48.288  D  读取缓存耗时132
12:40:50.761  D  scopeNetLife耗时1
12:40:50.786  D  读取缓存耗时24
12:40:52.434  D  scopeNetLife耗时3
12:40:52.456  D  读取缓存耗时22
12:40:53.745  D  scopeNetLife耗时4
12:40:53.763  D  读取缓存耗时18
tanranran commented 1 year ago

谢谢大佬解答,我这边在充分测试验证下