On Sat, Mar 28, 2009 at 3:16 PM, Marc <[email protected]> wrote: > So I have the following code... > > StringBuilder sb = new StringBuilder(4096); > > while (true) { > int i = in.read(); > if (i == 0) > break; > else if (i == -1) > throw new EOFException(); > sb.append((char)i); > } > > What I see (with thousands of times run) is that this code takes about > 1ms for every 7-10 bytes read... So reading just 10k takes almost a > SECOND! > > Can anyone explain this?
One guess is that the stream you are reading from isn't buffered, and so you may be going through a lot of layers of translation for each byte read, rather than getting them batched up and thereby handled more efficiently. Try using a BufferedInputStream (or a BufferedReader, see last paragraph below). As a minor efficiency point, rather than use a cascading if-else-if, you might want to use a switch statement. You don't say what physical platform you're running this on. If you are on a device connected via a cell network, this code could be running slow because your net connection is slow. 10k/second (aka 80kbps) is within the realm of possibility in a bad EDGE/3G coverage area. 10k/second is actually the fastest speed you can possibly expect with a 2G (GPRS) connection, according to Wikipedia. And if you are using an emulator, then all bets are off in terms of speed, since it would totally depend on the characteristics of your host platform. Note: If you are currently using an InputStream directly rather than a Reader, then the code above will only work with ISO-8859-1 encoded data. If you want to handle arbitrary encodings, you'll probably want to interpose an InputStreamReader. Cheers, -dan --~--~---------~--~----~------------~-------~--~----~ You received this message because you are subscribed to the Google Groups "Android Developers" group. To post to this group, send email to [email protected] To unsubscribe from this group, send email to [email protected] For more options, visit this group at http://groups.google.com/group/android-developers?hl=en -~----------~----~----~----~------~----~------~--~---

