I've done some performance testing with the OkHttp library and found it to be great. It did 80 requests to http://httpbin.org/delay/1, which deliberately pauses 1 sec for each request, in 4.7s on my HTC One phone. I've looked at the code and I'm trying to find out why it is so fast. The developers (Square Inc) advertise Connection Pooling and Async calls, both which I believe contribute to the good performance.
I come from the .NET world and in .NET 4.5 you have a true async HTTP library with an Async GetResponse-method. By yielding the thread to the OS while waiting for the response, you free up resources to initiate more HTTP requests, or other stuff. The thing is I cannot see the same pattern with OkHttp (or any other HTTP library for Android I've looked into). So how can I still execute 80 1-second-request in 4 seconds? It's not thread-based, right? I'm not firing up 80 (or 20) threads?
To be specific, in com.squareup.okhttp.Call.beginRequest(), I see no yielding of the thread between the sendRequest
and getResponse
calls:
if (canceled) return null;
try {
engine.sendRequest();
if (request.body() != null) {
BufferedSink sink = engine.getBufferedRequestBody();
request.body().writeTo(sink);
}
engine.readResponse();
} catch (IOException e) {
HttpEngine retryEngine = engine.recover(e, null);
if (retryEngine != null) {
engine = retryEngine;
continue;
}
// Give up; recovery is not possible.
throw e;
}
Response response = engine.getResponse();
So again, how is making 80 "parallell" calls possible?
I don't need to know this in order to use the library, but async programming interests me and I'd really like to understand how OkHttp/SquareInc has solved this.