For `x::Vector{Char}`, which should I use `string(x...)` or `join(x)`?

I have a black box variable x::Vector{Char} which satisfies length(x) < 20 (actually, it is not a black box because it is open source, but I do not understand how it behaves yet because I have not read the implementation in detail). Furthermore, the program uses string(x...) to convert x to String. I think join(x) do the same thing. Which is better?

1 Like

Just do String(x). That should also reuse the memory. It does not for Vector{Char} but nonetheless is by far the fastest option.

2 Likes

It’s approximately 6.67 times faster than string(x...)! Thanks!
スクリーンショット 2024-06-11 20.00.12

1 Like

Btw, these benchmarks are not quite accurate because x is untyped global and accessing these is slow. See the Performance tips (also a good read if you care about performance in Julia generally :wink: ). To avoid this in benchmark use interpolation with $.

I just put all these methods into functions and these are my results:

julia> using BenchmarkTools
julia> f1(x) = String(x)
julia> f2(x) = string(x...)
julia> f3(x) = join(x)

julia> x = rand(Char, 20);
julia> @btime f1($x);
  76.042 ns (1 allocation: 104 bytes)
julia> @btime f2($x);
  882.564 ns (21 allocations: 424 bytes)
julia> @btime f3($x);
  846.847 ns (5 allocations: 416 bytes)

julia> x = rand(Char, 2000);
julia> @btime f1($x);
  7.979 μs (1 allocation: 7.81 KiB)
julia> @btime f2($x);
  69.075 μs (2002 allocations: 54.81 KiB)
julia> @btime f3($x);
  66.002 μs (9 allocations: 11.73 KiB)

So for me the difference is more like ~9 times faster and also less allocations :slight_smile:

5 Likes

What actually happens when you splat 2000 values? I feared everything would go crazy, but apparently not.

1 Like

Hello,
As per me for converting a small Vector{Char} (x) into a String, string(x...) is generally better due to its straightforward and efficient conversion without needing a separator. It’s ideal for cases where length(x) < 20 and offers simplicity in implementation.
I hope this will help you,
Thank you

How is this better than String(x)? It’s less efficient, and more complicated.