# What's the fastest to convert a String to an \`Vector{T}\` where \`isbits(T) == true\` and back again?

**URL:** <https://discourse.julialang.org/t/whats-the-fastest-to-convert-a-string-to-an-vector-t-where-isbits-t-true-and-back-again/28458>\
**Category:** Performance\
**Created:** [September 6, 2019, 6:09am UTC](https://discourse.julialang.org/t/whats-the-fastest-to-convert-a-string-to-an-vector-t-where-isbits-t-true-and-back-again/28458 "2019-09-06T06:09:39Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![xiaodai](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/xiaodai/32/15937_2.png) [@xiaodai](https://discourse.julialang.org/u/xiaodai)\
**Post date:** [September 6, 2019, 6:09am UTC](https://discourse.julialang.org/t/whats-the-fastest-to-convert-a-string-to-an-vector-t-where-isbits-t-true-and-back-again/28458/1 "2019-09-06T06:09:39Z")

</div>

I want to see what’s the fastest way to convert a String to an invertible its binary representation (which I assume will be an array of type `T` for some `T`). The `codeunit` should do the trick but it used to be slow.

Also how do I go back from a bunch of `codeunit` back to a string?

```r
N = 1_000_000;
K = 100;

# faster string sort
svec = rand("id".*string.(1:N÷K, pad=10), N);

@time meh = reduce(vcat, codeunit.(svec, 1:length(svec)) for svec in svec) # takes too long

```

---

<div class="post-metadata">

**Author:** ![xiaodai](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/xiaodai/32/15937_2.png) [@xiaodai](https://discourse.julialang.org/u/xiaodai)\
**Post date:** [September 6, 2019, 6:14am UTC](https://discourse.julialang.org/t/whats-the-fastest-to-convert-a-string-to-an-vector-t-where-isbits-t-true-and-back-again/28458/2 "2019-09-06T06:14:47Z")

</div>

Is it `codeunits`? Also `unsafe_string(pointer(codeunits("string")))`

---

<div class="post-metadata">

**Author:** ![kristoffer.carlsson](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/kristoffer.carlsson/32/22_2.png) [@kristoffer.carlsson](https://discourse.julialang.org/u/kristoffer.carlsson)\
**Post date:** [September 6, 2019, 6:24am UTC](https://discourse.julialang.org/t/whats-the-fastest-to-convert-a-string-to-an-vector-t-where-isbits-t-true-and-back-again/28458/3 "2019-09-06T06:24:07Z")

</div>

`codeunits` will give you an iterator that iterates the bytes of the string. `String` goes from an array of bytes to a `String`.

```julia
julia> str = "fαβ"
"fαβ"

julia> cu_iterator = codeunits(str)
5-element Base.CodeUnits{UInt8,String}:
 0x66
 0xce
 0xb1
 0xce
 0xb2

julia> cu_array = collect(cu_iterator)
5-element Array{UInt8,1}:
 0x66
 0xce
 0xb1
 0xce
 0xb2

julia> String(cu_array)
"fαβ"

```

There are also unsafer versions like

```julia
julia> unsafe_wrap(Vector{UInt8}, str)
5-element Array{UInt8,1}:
 0x66
 0xce
 0xb1
 0xce
 0xb2

```
