Optimization 34: Byte-to-Char Conversions Previously, we saw the

Optimization 34: Byte-to-Char Conversions Previously, we saw the way converting Unicode characters to a byte stream could take a toll on performance. A similar issue exists in the reverse direction if a byte stream needs to be converted into Unicode characters. We have already encountered this issue in Optimization 4. There we recommended the use of a deprecated method to do the conversion when ASCII strings are involved. The politically correct way to convert a byte stream into a Unicode stream is by use of the FileReader, as in BufferedReader fr = new BufferedReader( new FileReader(”filename”)); String line = fr.readLine(); We tried this approach on our test loop by replacing the FileInputStream with a FileReader: BufferedReader fr = new BufferedReader( new FileReader(”stock.dat”)); String line = null; long start = System.currentTimeMillis(); // <+++ Start timingwhile ((line = fr.readLine()) != null) { // 100,000 iterations} long stop = System.currentTimeMillis();// <+++ Stop timing Execution time using the FileReader increased to 5.3 seconds. Recall from Optimization 33 that the very same code using a DataInputStream took only 4.7 seconds. See Figure 5.6. Figure 5.6. An InputStream is faster than a Reader The difference is due to the fact that the DataInputStream readLine() method is "cheating" by blindly casting a byte into a Unicode char. This step works only if the byte represents an ASCII character, but it is fast. If you know that your input byte stream is an ASCII stream, there's no harm Page 128
Note: If you are looking for cheap and reliable provider to host and run your servlet application check Vision servlet hosting services

Comments are closed.