Skip to content

Commit 0ec74f4

Browse files
committed
Speed up reading application metadata block
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.
1 parent b501bff commit 0ec74f4

File tree

2 files changed

+6
-2
lines changed

2 files changed

+6
-2
lines changed

src/metadata.rs

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77

88
//! The `metadata` module deals with metadata at the beginning of a FLAC stream.
99
10-
use std::iter;
1110
use error::{Result, fmt_err};
1211
use input::ReadBytes;
1312

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

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

274278
Ok((id, data))
Binary file not shown.

0 commit comments

Comments
 (0)