5

I have a file reader, which returns the lines of a file as an Object[]. I am using the lines method. Would it be faster to use readAllLines? I do not use the stream for anything else, but I want currentBookData to be a String[] or Object[].

package input;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Stream;

public class ReadFile {

    public static Object[] currentBookData;

    public static void getBookData(String path) throws IOException {
        try (Stream<String> stream = Files.lines(Paths.get(path), Charset.defaultCharset())) {
            currentBookData = stream.toArray();
        }

        catch (IOException ex) {
            System.out.println(ex.getMessage());
        }
    }

}
user207421
  • 305,947
  • 44
  • 307
  • 483
CaffeineToCode
  • 830
  • 3
  • 13
  • 25

2 Answers2

3
readAllLines() 

puts everything in memory in one time so nothing can be faster than that. Don't use it if your file is large.

Sezin Karli
  • 2,517
  • 19
  • 24
  • What if I have a 10,000 line file, would lines be superior? I'm assuming yes, because it does not do it all at once. – CaffeineToCode Dec 20 '14 at 22:51
  • I think if you have enough memory readAllLines() will beat everytime. why don't you try both with a large file and measure the time spent with System.nanotime() ? – Sezin Karli Dec 20 '14 at 22:58
  • Test complete. Results are on my answer. Strangly enough, the results say it took about 9000 seconds. While this is not true, the results are probably able to judge the faster method. Does the decimal show on the println method? – CaffeineToCode Dec 20 '14 at 23:38
  • How much large mean large? :) – KunLun May 13 '19 at 16:36
-2

For large files, lines is actually faster. The results were recorded with the nanoTime method. Here are the results:

lines: 890453203.00649

readAllLines: 891095615.58289

For the smaller files, readAllLines is faster.

CaffeineToCode
  • 830
  • 3
  • 13
  • 25
  • 5
    `0.0006` of a second faster is hardly a conclusive benchmark result, especially when I/O is involved! If you want to actually benchmark code in Java please use a framework like [JMH](http://openjdk.java.net/projects/code-tools/jmh/) – Matt Coubrough Dec 20 '14 at 23:48
  • You are correct, but I ran the test multiple times. These are the averages of the data. lines was faster each lime. – CaffeineToCode Dec 21 '14 at 00:03
  • 1
    Chances are that your "benchmark" is spending most of its time doing JVM warmup stuff. Your measurements are most likely not meaningful. – Stephen C Dec 21 '14 at 01:28
  • Once again, you are correct. I do not have the free time for a proper test right now. – CaffeineToCode Dec 21 '14 at 01:39
  • @CaffeineToCode thanks for your efforts. What is the size of the large file you used. – Christian Oliver Oct 11 '20 at 07:28