I wanted to compare how Java, C++ and C perform when reading a text file line by line and printing the output. I’ve implemented some possibilities and, at the end, we can compare the speed of each execution.
Java 7 version (BufferedReader)
import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; public class Main7 { private static final String FILENAME = "/path/to/file.txt"; public static void main(String[] args) throws IOException { File file = new File(FILENAME); BufferedReader br = new BufferedReader(new FileReader(file)); for (String line; (line = br.readLine()) != null; ) { System.out.println(line); } } }
Java 8 version (Stream)
import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.stream.Stream; public class Main8 { private static final String FILENAME = "/path/to/file.txt"; public static void main(String[] args) throws IOException { try (Stream stream = Files.lines(Paths.get(FILENAME))) { stream.forEach(System.out::println); } } }
C++ (ifstream)
#include < iostream> #include < fstream> #include < string> using namespace std; int main() { const constexpr char* FILENAME = "/path/to/file.txt"; ifstream file(FILENAME); string line; while (file.peek() != EOF) { getline(file, line); cout << line << '\n'; } file.close(); return 0; }
C (FILE)
#include < stdio.h> #include < stdlib.h> int main(void) { FILE* fp = fopen("/path/to/file.txt", "r"); if (fp == NULL) exit(EXIT_FAILURE); char* line = NULL; size_t len = 0; while ((getline(&line, &len, fp)) != -1) { printf("%s", line); } fclose(fp); if (line) free(line); exit(EXIT_SUCCESS); }
Performance
Below you can see how each program above performs reading a TXT file with 10,440 lines (file size is 3.5Mb).
Version | Time |
Java 7 (BufferedReader) | 0.254 seconds |
Java 8 (Stream) | 0.324 seconds |
C++ (ifstream) | 0.429 seconds |
C (File) | 0.023 seconds |
As we can see, C is by far the fastest option. I am surprised that C++ isn’t faster than Java, but this is probably because of the ifstream and std::getline() implementation. This is not the first time I see the Standard Library with performance issues compared to other languages (the regular expression implementation was the first time).