Skip to content

Commit

Permalink
Speed up reading application metadata block
Browse files Browse the repository at this point in the history
I used to fill the buffer with zeros before, but they would be
overwritten later anyway. This is not such an issue, except that filling
this buffer with zeros by using an iterator, is apparently terribly
inefficient.

The performance difference in debug mode is as much as a factor 1000.
From ~2.3 seconds to 0.0025 seconds. In release mode this does not
matter so much.

This issue was discovered as a slow case using libfuzzer and cargo-fuzz.
  • Loading branch information
ruuda committed Feb 23, 2017
1 parent b501bff commit 0ec74f4
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/metadata.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@

//! The `metadata` module deals with metadata at the beginning of a FLAC stream.

use std::iter;
use error::{Result, fmt_err};
use input::ReadBytes;

Expand Down Expand Up @@ -268,7 +267,12 @@ fn read_application_block<R: ReadBytes>(input: &mut R, length: u32) -> Result<(u
let id = try!(input.read_be_u32());

// Four bytes of the block have been used for the ID, the rest is payload.
let mut data: Vec<u8> = iter::repeat(0).take(length as usize - 4).collect();
// Create a vector of uninitialized memory, and read the block into it. The
// uninitialized memory is never exposed: read_into will either fill the
// buffer completely, or return an err, in which case the memory is not
// exposed.
let mut data = Vec::with_capacity(length as usize - 4);
unsafe { data.set_len(length as usize - 4); }
try!(input.read_into(&mut data));

Ok((id, data))
Expand Down
Binary file not shown.

0 comments on commit 0ec74f4

Please sign in to comment.