简体   繁体   中英

Android InputStream.read() horribly slow

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.

My 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++;
}

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.

You're reading 1 byte at a time. That's incredibly inefficient. YOu want to read a large number of bytes at once- as much as possible. That's the reason your app is slow.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM