pires / obd-java-api

OBD-II Java API
Apache License 2.0
594 stars 295 forks source link

I/O Streams #133

Open PanagiotisDrakatos opened 7 years ago

PanagiotisDrakatos commented 7 years ago

I found,that your way to deal with the raw bytes of elm327 not so efficiency, this is because you deal with characters (read until '>' appear) so you need a bridge from byte streams to character streams. InputStreamReader are used specifically to deal with characters.

For more efficiency, consider wrapping an InputStreamReader within a BufferedReader. For example take consider the below example to read the data from ELM327 Protocol.

public String readUntilChar( InputStream in,char target) {
        StringBuilder sb = new StringBuilder();

        try {
            int bufferSize = 8 * 1024;
            BufferedReader buffer = new BufferedReader(new InputStreamReader(in), bufferSize);
            int r;
            while ((r = buffer.read()) != -1) {
                char c = (char) r;
                if (c == target)
                    break;
                sb.append(c);
            }
            System.out.println(sb.toString());
        } catch (IOException e) {
            // Error handling
        }

        return sb.toString();
    }

The BufferedReader class (java.io.BufferedReader) supplies buffering to your Reader. Thus, buffering can speed up I/O stream quite a bit. So instead read one character at a time from the network, the BufferedReader reads a larger block at a time. This is typically much faster and more efficient, especially for larger data amounts.The efficient conversion of bytes to characters, carried out with more bytes to read ahead from the stream than are necessary to satisfy the current read process.

pires commented 7 years ago

Open a PR and prove your assertions with benchmarks please.

PanagiotisDrakatos commented 7 years ago

i wish i had 1 dollar each time i post something for improvement. I am working on a same project and the matter of I/0 stream performance is critical to me so i decided to post my way to handle the I/O as i explained before. In contrast with your recent code, it does not fit with my expectations due to the performance of I/0 stream. I think i was explained detailed the improvement and my point is so obvious, but i also agree you need assertions to be proved with benchmarks. i will try add it in the near future or else i will try release something similar with benchamarks

pires commented 7 years ago

I totally understand. Thank you :)