0

I made two unix cat examples in Java but both were very slow compared to C++

[Java Example 1]

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
 
public class BufferedCat {
    public static void main(String[] args) throws IOException {
        String path = args[0];
        FileReader file = new FileReader(path);
 
        BufferedReader buffReader = new BufferedReader(file);
        
        int c = buffReader.read();
        while(c != -1) {
            System.out.print((char)c);
            c = buffReader.read();
        }
        buffReader.close();
    }
 
}

[Java Example 2]

import java.io.File;
import java.io.IOException;
import java.util.Scanner;
 
public class ScannerCat {
    public static void main(String[] args) throws IOException {
        String path = args[0];
        
        Scanner scanner = new Scanner(new File(path));
        
        while(scanner.hasNext()) {
            System.out.println(scanner.nextLine());
        }
        
        scanner.close();
 
    }
 
}

[C++ Example 3 ]

#include <iostream>
#include <fstream>
#include <string>
using namespace std;
 
int main (int argc, char **argv) {
  string line;
  ifstream myfile (argv[1]);
  if (myfile.is_open())
  {
    while ( getline (myfile,line) )
    {
      cout << line << '\n';
    }
    myfile.close();
  }
 
  else cout << "Unable to open file"; 
 
  return 0;
}

Example two is much faster than the first, but it's not quite like C++ I'm using this file and file2 as a test, As I'm a beginner in java, I believe that I don't know how to correctly use the IO.

I know java is a language that compiles to bytecode and runs in the JVM and it won't perform as high as C++, but I'm pretty sure the problem lies in the implementation of my simple cat. So i want to helps you guys on how to use IO in java effectively

  • 1
    A lot to think about here. So, yes, Java can be pretty fast ... mainly for LONG running stuff. Because then the Just In Time Compiler can come in and turn your bytecode into machine code. **That** is when Java can be faster than C++. But here, you pay the full overhead of the virtual machine concept, as depending on the size of your file, MOST time will be spend starting up the JVM. So: if you want to do realistic measuring, then create timestamps right before opening the input file, and then again when you printed the last line. Compare those numbers! – GhostCat Jan 05 '22 at 15:55
  • And then ... see the first comment here: https://stackoverflow.com/questions/3857052/why-is-printing-to-stdout-so-slow-can-it-be-sped-up ... and yeah, try that: compare if there is a difference writing to files, instead of stdout directly. – GhostCat Jan 05 '22 at 15:57
  • You may see better performance with newer APIs, like `Files.copy(Path.of(args[0]), System.out);` or `FileChannel.open(Path.of(args[0])).transferTo(0, Long.MAX_VALUE, Channels.newChannel(System.out));`. – VGR Jan 05 '22 at 20:33

0 Answers0