Android的InputStream.read()异常缓慢 [英] Android InputStream.read() horribly slow

查看:421
本文介绍了Android的InputStream.read()异常缓慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个Android应用程序,需要有这也是我写的一台服务器(我的电脑上运行)进行通信。
问题是,InputStream.read()接受一个永恒的,加工200KB需要30秒左右的东西。也许垃圾收集涉及不知怎的,我的循环期间,它被调用不时但上市延迟只有2个或3 millisecods和所有的一切,也许20毫秒,所以我不认为这是问题。

I'm working on an Android app that needs to communicate with a server (running on my PC) which is also written by me. The problem is that InputStream.read() takes an eternity, processing 200kb takes something around 30 seconds. Maybe the garbage collection is involved somehow, during my loop it gets called from time to time but the listed delays are only 2 or 3 millisecods and all in all maybe 20ms so I don't think that's the problem.

我的code:

client = new Socket("192.168.1.1", 1235);
client.setTcpNoDelay(true);
client.setReceiveBufferSize(1048576);
InputStream is = client.getInputStream();

byte[] buffer = new byte[1048576];
int i = 0;
int length = -1;

while (true)
{
    int b = is.read();
    if (b == -1)
    {
        success = false;
        break;
    }
    buffer[i] = (byte) b;

    if (i == length)
        break;

    if (i == 3)
    {
        length = buffer[0] | buffer[1] << 8 | buffer[2] << 16 | buffer[3] << 24;
    }

    i++;
}

我没有真正经历Java和Android中编程初学者总让我不知道为什么它是那该死的缓慢。

I'm not really experienced in Java and a total beginner in Android programming so I have no idea why it's that damn slow.

推荐答案

为什么要单独看每个字节?它看起来像你真正想要阅读的前3个字节,并找出你的长度,然后读取该块。

Why are you reading each byte individually? It looks like you really want to read the first 3 bytes and figure out your length and then read that block.

IE:

final byte[] lengthBuffer = new byte[3];

int b = is.read(lengthBuffer);

// make sure b was 3 and do your length calculation

final byte buffer = new byte[length];

b = is.read(buffer);

// check b and then you have your bytes

然后你至少可以得到的InputStream可以提供在同一时间读取数据块,而不是一个字节的优化。而你不分配像你这样的大型阵列目前拥有。

Then you can at least get the optimizations that Inputstream can provide for reading blocks of data rather than one byte at a time. And you are not allocating that mega array like you currently have.

这篇关于Android的InputStream.read()异常缓慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆