# Read a single element vs array from stream

**URL:** <https://discourse.julialang.org/t/read-a-single-element-vs-array-from-stream/66328>\
**Category:** General Usage\
**Tags:** question, binaryio, dispatch\
**Created:** [August 13, 2021, 9:22am UTC](https://discourse.julialang.org/t/read-a-single-element-vs-array-from-stream/66328 "2021-08-13T09:22:44Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![Bardo](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bardo/32/21601_2.png) [@Bardo](https://discourse.julialang.org/u/Bardo)\
**Post date:** [August 13, 2021, 9:22am UTC](https://discourse.julialang.org/t/read-a-single-element-vs-array-from-stream/66328/1 "2021-08-13T09:22:44Z")

</div>

Since the single case is used often, I use read1T as a convenience function.

Novice question: can the two functions be combined without violating type stability?

Or, more generally, does Union{T, AbstractArray{T}} as input or output type already get a performance hit?

```julia
function readnT(io, n, T, Tr)
    s = sizeof(T)
    f = UInt8[s]
    readbytes!(io, f, n*s)
    return Tr.(reinterpret(T, f))
end

function read1T(io, T, Tr)
    s = sizeof(T)
    f = UInt8[s]
    readbytes!(io, f, s)
    return Tr.(reinterpret(T, f))[1]
end

```

---

<div class="post-metadata">

**Author:** ![Vasily\_Pisarev](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/vasily_pisarev/32/7929_2.png) [@Vasily\_Pisarev](https://discourse.julialang.org/u/Vasily_Pisarev)\
**Post date:** [August 13, 2021, 10:55am UTC](https://discourse.julialang.org/t/read-a-single-element-vs-array-from-stream/66328/2 "2021-08-13T10:55:42Z")

</div>

Have you tried `read(io, T)` and `read!(io, array)` from the standard library?  
The first reads one value of `T`, the second reads until `array` is full.

---

<div class="post-metadata">

**Author:** ![Bardo](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bardo/32/21601_2.png) [@Bardo](https://discourse.julialang.org/u/Bardo)\
**Post date:** [August 13, 2021, 12:13pm UTC](https://discourse.julialang.org/t/read-a-single-element-vs-array-from-stream/66328/3 "2021-08-13T12:13:27Z")

</div>

interesting way to read the correct amount of data, thx!

---

<div class="post-metadata">

**Author:** ![Bardo](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/bardo/32/21601_2.png) [@Bardo](https://discourse.julialang.org/u/Bardo)\
**Post date:** [August 13, 2021, 9:37pm UTC](https://discourse.julialang.org/t/read-a-single-element-vs-array-from-stream/66328/4 "2021-08-13T21:37:27Z")

</div>

Continued [here](https://discourse.julialang.org/t/transmit-and-receive-a-string-julia-1-6/66362).
