0

I'm looking to write an iterator Item = u8 to a file. The iterator has a large len so collecting the iterator and then writing the resulting vector isn't very efficient.

I'm thinking of collecting chunks of the iterator and writing chunk by chunk but that also doesn't seem particularly efficient, is there a better/more efficient way to do it (Ideally something which allows me to pipe the iterator strait into a Bufwriter or similar)?

Thanks

12
  • 3
    Just use BufWriter and write a single byte at a time. BufWriter will take care of the buffering. Commented May 9 at 9:13
  • @AleksanderKrauze ok but how? All the methods on bufwriter that I can see take a slice of u8's i.e. &[u8] rather than a single u8 and I'm assuming that there would be a performance overhead from converting each byte into a slice i.e. buf_writer.write(&[byte]) Commented May 9 at 9:27
  • 1
    maybe in the debug builds. But in the release build all of this should be optimised away. Did you measured performance, or are you just worrying in advance? Commented May 9 at 9:59
  • 1
    It won't be very efficient, but there is nothing you can really do if your source is truly just a stream of bytes. You may want to pool multiple bytes into a small buffer, and hand that off to BufWriter; but that kind of pooling is exactly what BufWriter already does, and does so as efficient as it gets. Long story short, as @AleksanderKrauze said: Either write single-byte slices into a BufWriter, or redesign the source. Avoid the temptation to copy buffers from buffers into other buffers. Commented May 9 at 11:26
  • 1
    @Pioneer_11 "I'm assuming that there would be a performance overhead from converting each byte into a slice" not really, all that happens is that the byte gets copied from register to stack if not already on the stack, then the address of that is taken, a "1" is added next to it, and bam you have a slice. The actual calling of write for each byte is going to be way more costly than converting a byte into a byte slice. Commented May 9 at 12:29

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.