About File.rawWrite

Denis Shelomovskij verylonglogin.reg at gmail.com
Tue Nov 29 07:00:47 PST 2011


29.11.2011 15:57, bearophile пишет:
> This D2 program runs in about 5.13 seconds on my PC:
>
>
> import std.stdio;
> void main() {
>      auto f = File("bytes_test.dat", "wb");
>      ubyte[3] RGB;
>      foreach (_; 0 .. 1_000_000)
>          f.rawWrite(RGB);
> }
>
>
>
> While this C program runs in about 0.14 seconds:
>
>
> #include<stdio.h>
> int main() {
>      FILE *f = fopen("bytes_test.dat", "wb");
>      unsigned char RGB[3] = {0};
>      int i;
>      for (i = 0; i<  1000000; i++)
>          fwrite(RGB, 1, 3, f);
>      return 0;
> }
>
>
> Is my D2 program wrong, or is File.rawWrite in need of some improvements?
>
> (Writing 3 bytes at a time is not efficient, but the C code shows that the runtime is acceptable for me for small files).
>
> Bye,
> bearophile

Your OS is Windows, right? On Windows, rawWrite and rawRead always 
flushes stream, sets binary mode, reads/writes, flushes stream again, 
sets previous mode. This is definitely unnecessary slow - at least it 
should change mode only if needed (the file is opened in a text mode). 
The better solution is to change all other functions so the file mode 
will be changed lazily (for a text file, raw* functions will change file 
mode and leave file in this mode until a call of a function, that really 
needs a file to be in a text mode).

By the way, why this changing mode behaviour is Windows only? Yes, it is 
clearly documented that this is the case, but it isn't documented _why_ 
this is the case.

Quick link to the current rawRead implementation (for happy owners of 
Google's Chrome, the fastest beautiful web browser that can BSOD your 
Windows even without administrator rights) (the link isn't for Firefox: 
it will slow down the browser and be displayed incorrectly):
https://github.com/D-Programming-Language/phobos/blob/master/std/stdio.d#L458


More information about the Digitalmars-d-learn mailing list