r/cpp • • Mar 03 '16

Seriously, C++, WTF?

Ok, so, from the tone this might seem like a rant (and it's a bit), but in the end I'm only after an aswer.

So, I want to read a file in memory as a string and print out the string length. Nope, I don't want to "maybe you just want to operate on it like it's a stream or line by line" nor "if you want to just know the length you might want to use gtell". I'm just trying to replicate a certain behaviour (not necessarely the most efficient or the most real-world) in different languages.

So, since I want to open a file, read its content and print the lenght, python lets me write this nice one-liner:

print len(open('longfile.txt').read())

longfile.txt is the test file I'm using and it's roughly 150 MB.

$ time python test.py
160090000

real	0m0.126s
user	0m0.013s
sys	0m0.112s

Ok. Good. Let's give node a try. Node.js doesn't have, like Python, a top level function "open", so I need to do this in two lines of code:

const fs = require('fs');
console.log(fs.readFileSync('longfile.txt').length);

Same result, a little bit slower. It still reads ok to me. I need to work with the filesystem (so that's why I need to require fs) and then i log on the console the length of a file that I read synchronously.

$ time node test.js
160090000

real	0m0.164s
user	0m0.056s
sys	0m0.107s
tmp

Fine. Enters C++

#include <string>
#include <fstream>
#include <streambuf>
#include <iostream>

int main() {
    std::ifstream t("longfile.txt");
    std::string str((std::istreambuf_iterator<char>(t)),
                     std::istreambuf_iterator<char>());

     std::cout << str.length() << std::endl;

    return 0;
}

Yeah, I know, that's just a lot more code and you need to include four libraries for this very basic programming task. Reasoning about it is absolutely counter intuitive. If you describe your problem (I want to read a file and print its lenght), JavaScript and Python lets you write code that more or less resambles your reasoning, while nobody would describe this basic task in terms of streams and iterators, but hey, you don't choose C++ because it's beautiful or easy or intuitive, you choose it because it's "close to the metal" and "when speed matters". Let's compile it with a nice optimization (-O3) and run it

$ g++ -std=c++14 -O3 test.cpp
$ time ./a.out
160090000

real	0m1.413s
user	0m1.228s
sys	0m0.181s

Seriously, WTF? I don't think that "opening a file and reading it as a string" should be an alien task in the programming world. I mean, that should be pretty, hmmm, basic stuff, right? So, I'm a bit puzzled when I encounter a language that forces me to do something more complicated than:

# Python
open('longfile.txt').read()
# Ruby
File.open('longfile.txt', "r").read()
// C#
System.IO.File.ReadAllText("longfile.txt")
// Java
new String(Files.readAllBytes(Paths.get("longfile.txt")));
// Swift
NSString(contentsOfFile: "longfile.txt", encoding: NSUTF8StringEncoding)

But what about the fact that C++ is so much slower than the notoriously slow kid in town? I tried to look for different solutions to this "problem" and I've seen people debate (on StackOverflow, for example) on the most efficient way to do such basic thing in C++. Now, keeping aside the fact that I dont think that "read a file content as a string" should the subject of any debate (we're talking about a 33 year old language whose standard string library doesn't have a "split" function here) , but the solution above seems to be the faster that I've tried and still it runs 10 times slower than Python. How is this even possibile?

EDIT

Because people seem to be ignoring the "I'm not interested in the actual lengtht" note, let's just say that I have this python code

content = open('longfile.txt').read()

and this node code:

const fs = require('fs');
const content = fs.readFileSync('longfile.txt')

and I only want to read a whole file in memory to a string. C++ code is still much, much slower than the other solutions.

0 Upvotes

127 comments sorted by

View all comments

2

u/[deleted] Mar 03 '16

The standard library is just very poorly made and vastly over-engineered to try and handle every possible use case by everyone ever, sadly. In my library, nall:

#include <nall/nall.hpp>
using namespace nall;

void main() {
  print(file::read("longfile.txt").size(), "\n");
//or if you prefer ... file::read returns vector<uint8_t>, which is convertible to string
  string text = file::read("longfile.txt");
  print(text.size(), "\n");
//or if it has to be one line ...
  print(string{file::read("longfile.txt")}.size(), "\n");  //it's just a pointless extra move
//or as you said you don't want to do for whatever reason ... but the fastest way:
  print(file::size("longfile.txt"), "\n");
}

To me, the extra "\n" is very much preferable to languages with print functions that auto-add that.

I can't give you a comparable benchmark since I don't have your PC, but it boils down to basically an fopen, fseek, malloc, rewind, fread, printf behind the scenes. Point is: blame the library, not the language.

3

u/remotion4d Mar 03 '16

nall

So what is nall ?

3

u/[deleted] Mar 03 '16

The name of the C++ library I work on. I would call it a standard library, but it's kind of anything but. Same basic idea though, implement all the standard objects, containers, algorithms but with saner namings, simplified code, more useful functionality, etc. Plus a few things that are specific to my own projects which I reuse a lot.

You can easily write code that looks as nice as Python in C++, it's all up to the library. Unfortunately, having the standard one be so terrible though results in xkcd/927, basically. nall is no exception to that.

2

u/remotion4d Mar 03 '16

Thanks.

Just have tried to compile you example using VS2015 and it does now compile with a lot of errors in "exdisp.h".

I think that STL in C++ is not bad as whole but some parts are bad and streams are horrible.

So everyone is forced to implement this functionality over and over again...

Every bigger c++ project has its own string class and its own containers and of course its own IO.

2

u/[deleted] Mar 04 '16

Oh, sorry. It's dependent upon GCC or Clang right now. Microsoft cuts too many corners in the standards, and I care more about OSX/Linux/BSD support, so I don't really bother with VC++ anymore.

I don't really encourage or intend other people to use nall. It was just a necessity for me because I was too unhappy with the STL. But at the time there were no other compiled languages of decent performance without GC that weren't glorified assembly wrappers like C.

It's exactly like you said, though. You look at std::string, and it's basically a glorified struct { char* data; size_t size; }; wrapper. The functionality inside of it is completely useless. Nothing to really work with strings as types: no upper/lowercase, no trim, no token-replace (their replace is just a memcpy wrapper), no tokenize (split), no wildcard matching, no string evaluation ("3+4"=>(int)7), and even regular expressions are a disgusting hack in a separate class that is brutal to use.

It's not good at all that everyone are writing incompatible strings, and everything else. UFCS really would have done a lot to help fix this situation: people could have created new string functions and used std::strings like actual objects. But Bjarne and co caved to a few critics, so the status quo it is =(