为什么与 PC 相比,Android 中的响应时间(对于休息呼叫)更慢?

2023-12-20

I am making a rest api call from Android device and was really surprised looking at the difference of speeds when compared to PC. Below is the image from a rest tool on PC.enter image description here

我尝试了一些库,例如 Retrofit、Volley 以及常规异步任务,以从 Android 设备进行相同的休息调用,并注意到以下响应时间。

(Response times with Retrofit library (Time includes converting json data to java objects)).
Test 1: 8372 Ms
Test 2: 7715 Ms
Test 3: 7686 Ms
Test 4: 10128 Ms
Test 5: 7876 Ms

(Response times with Volley. No conversion to Java Objects from Json Data )
Test 1: 6721 MS
Test 2: 6610 MS
Test 3: 6287 MS
Test 4: 6118 MS
Test 5: 6118 MS

I took System.currentTimeMillis()在拨打电话之前和获得响应之后减去这些值即可得到 Android 程序中的上述响应时间。

如果有人能告诉我如何减少 android 中的响应时间,那将非常有帮助。

仅供参考:我使用 Wifi,并为我的 PC 和 Android 设备使用相同的网络。

这是改造Android代码

RestAdapter adapter = new RestAdapter.Builder()
                                .setEndpoint(ENDPOINT)
                                .build();

    WeatherApi weatherApi = adapter.create(WeatherApi.class);
    startTime = System.currentTimeMillis();
    weatherApi.getWeather(location.getLatitude(),location.getLongitude(),new Callback<WeatherInfo>() {

        @Override
        public void success(WeatherInfo arg0, Response arg1) {
            endTime = System.currentTimeMillis();
            Log.d("TAG",endTime-startTime + ":Millisecs");
            setWeatherInfo(arg0);
            if(weatherDialog != null && weatherDialog.isShowing())
            weatherDialog.dismiss();
        }

Retrofit 对其使用的 HTTP 客户端是不可知的,因此它会尝试找出可用于执行请求的最佳可用 HTTP 客户端。

默认情况下,Retrofit 使用 GSON 作为转换器(也可以自定义)。考虑到 GSON 使用反射将 JSON 元素映射到类属性,WeatherInfo类很可能在转换步骤上有性能损失。

由于您的情况的差异不太合理,我最好的猜测是 GZIP 被禁用。您可以使用RestAdapter.setLogLevel(LogLevel.FULL)并检查Accept-Encoding标头以查看 GZIP 是否启用。如果情况并非如此,请发布更多相关代码,以便我们提供更多见解。

我相信您会注意到一个巨大的区别的快速方法是,如果您包含 okhttp 和 okhttp-urlconnection - 当它们在类路径中可用时,Retrofit 默认情况下将使用 okhttp 作为客户端,它支持 GZIP,无需任何进一步的配置。

您可以通过将以下依赖项添加到 build.gradle 文件中来实现此目的:

compile 'com.squareup.okhttp:okhttp:2.4.0'
compile 'com.squareup.okhttp:okhttp-urlconnection:2.4.0'

请注意,服务器端也必须支持压缩,我不确定您是否已发布响应标头的完整输出,但它似乎缺少类似的内容Content-Encoding: gzip,如果是这种情况,您也应该考虑在您的网络服务器上启用此功能。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

为什么与 PC 相比,Android 中的响应时间(对于休息呼叫)更慢? 的相关文章

随机推荐