Home > OS >  Should I prefer FileReader to BufferedReader while reading CSV?
Should I prefer FileReader to BufferedReader while reading CSV?

Time:11-23

In a Spring Boot app, I am reading csv file data using OpenCSV and it is possible to use FileReader to BufferedReader with it. However, when I compare both of them, I have a dilemma for the following point:

BufferedReader is faster than FileReader, but it uses much more memory.

As I am reading multiple data file (having hundreds of thousands records) in the same method (first I read data from one csv and then use the retrieved id fields to read the second csv), I think I shouldn't use BufferedReader for less memory usage. But I am really not sure what is the most proper way.

So, in this situation, Should I prefer FileReader to BufferedReader?

CodePudding user response:

As far as i know the difference in size lies simply in the buffer size, which by default is 8k or 16k, so the difference is memory isn't huge; the most important thing is you remember to free the resources when you don' use them anymore, calling close(), also remember to do it incase of Exceptions

CodePudding user response:

Generally speaking, depends on your constraints. If performance is an issue, allocate more resources and go for the faster solution. If memory is an issue, do the reverse.

With BufferedReader you can also use the reader and int constructor to set buffer size, which suits your needs.

BufferedReader reader = new BufferedReader(Reader, bufferSize);

Another general rule of thumb, don't do premature optimizations, be it memory or performance. Strive for clean code, if a problem arises, use a profiler to identify the bottlenecks and then deal with them.

  • Related