Reading text files line by line: Java, C++ and C benchmark

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)


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; ) {

Java 8 version (Stream)

import java.nio.file.Files;
import java.nio.file.Paths;

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))) {

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';
   return 0;


#include < stdio.h>
#include < stdlib.h>

int main(void)
   FILE* fp = fopen("/path/to/file.txt", "r");
   if (fp == NULL)

   char* line = NULL;
   size_t len = 0;
   while ((getline(&line, &len, fp)) != -1) {
      printf("%s", line);

   if (line)


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).



Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s