# Create an indexed line from a vector

**URL:** <https://discourse.julialang.org/t/create-an-indexed-line-from-a-vector/114783>\
**Category:** Performance\
**Created:** [May 27, 2024, 1:45pm UTC](https://discourse.julialang.org/t/create-an-indexed-line-from-a-vector/114783 "2024-05-27T13:45:16Z")\
**Posts on this page:** 1\
**Showing post:** 5

<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:** [May 28, 2024, 1:57pm UTC](https://discourse.julialang.org/t/create-an-indexed-line-from-a-vector/114783/5 "2024-05-28T13:57:20Z")

</div>

> [@zweiglimmergneis](#):
>
> It would be nice to have a version of `string()`, where you can reuse the buffer.

`print` to an `IOBuffer`. (This is what `string` does internally anyway.) For even more re-use, you can make a non-destructive `String`-like view of an `IOBuffer` with [StringViews.jl](https://github.com/JuliaStrings/StringViews.jl).

> [@Sevi](#):
>
> So far the fastest I could get is ditching `writedlm` altogether and just writing everthing manually after `join`ing the lines together… 😅
> 
> ```julia
> function to_file(v, filename)
> open(filename, "w") do file
> write(file, "0\n")
> write(file, join((string(i) * ":" * string(val) for (i,val) in pairs(v)), '\n'))
> end
> end
> 
> ```

Should be better still to ditch the `string` and `join` calls entirely and just `print` directly to the file, e.g. something like:

```julia
function to_file(v, filename)
    open(filename, "w") do file
        println(file, 0)
        for (i, val) in pairs(v)
            println(file, i, ':', val)
        end
    end
end

```

(which is also more readable than the `join` version in my opinion). Note that I use [`print` instead of `write`](https://discourse.julialang.org/t/difference-between-write-and-print/6943/2) to output the text representations of `i` and `val` directly. You could also use `enumerate` instead of `pairs` to allow `v` to be an iterator rather than a vector (and to guarantee that the output indices start at `1`).

A version of this idea is also in the Julia [performance tips (“Avoid string interpolation for I/O”)](https://docs.julialang.org/en/v1/manual/performance-tips/#Avoid-string-interpolation-for-I/O): don’t construct an intermediate string just to write it to a file.

---

_[View the full topic](https://discourse.julialang.org/t/create-an-indexed-line-from-a-vector/114783)._
