# String optimisation in Julia

**URL:** https://discourse.julialang.org/t/string-optimisation-in-julia/119301
**Category:** General Usage
**Tags:** performance, strings, io
**Created:** [September 11, 2024, 10:56pm UTC](https://discourse.julialang.org/t/string-optimisation-in-julia/119301 "2024-09-11T22:56:05Z")
**Posts on this page:** 1
**Showing post:** 10

<div class="post-metadata">

### Author: ![stevengj](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/stevengj/32/71_2.png) [@stevengj](https://discourse.julialang.org/u/stevengj)
#### Post date: [September 12, 2024, 12:21pm UTC](https://discourse.julialang.org/t/string-optimisation-in-julia/119301/10 "2024-09-12T12:21:15Z")

</div>

> [@greatpet](#):
>
> [Vararg functions](https://docs.julialang.org/en/v1/manual/functions/#Varargs-Functions) are often type-unstable. For example,
> 
> ```julia
> buf = IOBuffer()
> @code_warntype print(buf, " J ", 1)
> 
> ```

This is because `for` loops over a heterogeneous tuple are type-unstable. As discussed in [For statement type instability - #7 by stevengj](https://discourse.julialang.org/t/for-statement-type-instability/118817/7), however, it’s possible to fix this by unrolling, and should be a simple 1-line patch to change [the `print` definition](https://github.com/JuliaLang/julia/blob/945517ba4e15f7470b8790a696ba5404ef047f2f/base/strings/io.jl#L42-L52) to something like:

```julia
function myprint(io::IO, xs...)
    lock(io)
    try
        foreach(xs) do x
            print(io, x)
        end
    finally
        unlock(io)
    end
    return nothing
end

```

which should be type-stable and hopefully should perform better. (Similarly for [`Base.print_to_string`](https://github.com/JuliaLang/julia/blob/945517ba4e15f7470b8790a696ba5404ef047f2f/base/strings/io.jl#L137-L151) and `Base.string_with_env`.) Anyone want to submit a PR?

As for `write(io, string(n))` vs. `print(io, n)`, I’m not sure what is going on (if there is really a difference?), because `print(io, n)` calls [`show(io, n)` which calls `write(io, string(n))`](https://github.com/JuliaLang/julia/blob/master/base/show.jl#L1244) already?

(However, the fact that writing an integer to a stream requires allocation of a string, for `string(n)`, is certainly hurting us in writing to an `IOBuffer` where writes are fast. At least in the `IOBuffer` case, we should in principle be able to use a view into the `IOBuffer` itself as the necessary buffer. The downside of this would be needing a long list of specialized `IOBuffer` methods for `show`, unless we do some clever refactoring.)

---

_[View the full topic](https://discourse.julialang.org/t/string-optimisation-in-julia/119301)._
