JuliaLang/julia — comment on commit 3f753435f137cd39afb0ffbdf4fc777efb03c6dd
File:  line 0
By StefanKarpinski:

The current printf code only does an enormous number of function calls for everything because it can't write directly into the print buffer and I wanted to avoid allocating an intermediate string and then printing it. However, it seems that as things stand, writing the full output to an intermediate buffer and then making a single `write` call to copy that entire string to the output buffer would be much more efficient because of all the overhead involved in `write`. It's annoying to have to have an intermediate buffer for this though. I'd much rather have direct access to the print buffer. If the I/O system were written in Julia we could have this, and it wouldn't be problematic to make a bunch of function calls as long as they could get inlined. C function calls, of course, can't get inlined.

The `NaN` tests are necessary because `%d` can handle float values as well as integers, and prints the correct value regardless of type:

```
julia> sprintf("%d", realmax())
"179769313486231570814527423731704356798070567525844996598917476803157260780028538760589558632766878171540458953514382464234321326889464182768467546703537516986049910576551282076245490090389328944075868508455133942304583236903222948165808559332123348274797826204144723168738177180919299881250404026184124858368"
```

In the case of an integer argument, `isfinite(x)` is always true and it just gets on with printing the value. This is a good case for the function returned by `f"%d"` being generic so that it can have methods specialized to the argument type. That would avoid the second level of dispatch that's done by the `_jl_fix10`, `_jl_sig10`, etc. function that interpret different types of values different ways.

The same generality is true of `%f`: it can handle integer values just as well as floating-point values. And it prints them accurately regardless of whether they are representable exactly as floats:

```
julia> sprintf("%f", typemax(Uint64))
"18446744073709551615.000000"
```

I think that both of these functionalities are in keeping with our approach to numerical accuracy.