From 46b8f84d6aa947a1ccfc9c845a2c3760a5bf15e4 Mon Sep 17 00:00:00 2001 From: JasonLG1979 Date: Fri, 23 Jun 2023 12:00:42 -0500 Subject: [PATCH] Make sure there is only ever one allocation when converting Collect is probably fine but for code that's this hot it's worth the couple extra lines to make certain there's only ever one allocation when it comes to the returned Vec. --- playback/src/convert.rs | 58 +++++++++++++++++++++++++++++------------ 1 file changed, 41 insertions(+), 17 deletions(-) diff --git a/playback/src/convert.rs b/playback/src/convert.rs index a7efe452..f825490c 100644 --- a/playback/src/convert.rs +++ b/playback/src/convert.rs @@ -80,36 +80,60 @@ impl Converter { } pub fn f64_to_f32(&mut self, samples: &[f64]) -> Vec { - samples.iter().map(|sample| *sample as f32).collect() + let mut output = Vec::with_capacity(samples.len()); + + output.extend(samples.iter().map(|sample| *sample as f32)); + + output } pub fn f64_to_s32(&mut self, samples: &[f64]) -> Vec { - samples - .iter() - .map(|sample| self.scale(*sample, Self::SCALE_S32) as i32) - .collect() + let mut output = Vec::with_capacity(samples.len()); + + output.extend( + samples + .iter() + .map(|sample| self.scale(*sample, Self::SCALE_S32) as i32), + ); + + output } // S24 is 24-bit PCM packed in an upper 32-bit word pub fn f64_to_s24(&mut self, samples: &[f64]) -> Vec { - samples - .iter() - .map(|sample| self.clamping_scale(*sample, Self::SCALE_S24) as i32) - .collect() + let mut output = Vec::with_capacity(samples.len()); + + output.extend( + samples + .iter() + .map(|sample| self.clamping_scale(*sample, Self::SCALE_S24) as i32), + ); + + output } // S24_3 is 24-bit PCM in a 3-byte array pub fn f64_to_s24_3(&mut self, samples: &[f64]) -> Vec { - samples - .iter() - .map(|sample| i24::from_s24(self.clamping_scale(*sample, Self::SCALE_S24) as i32)) - .collect() + let mut output = Vec::with_capacity(samples.len()); + + output.extend( + samples + .iter() + .map(|sample| i24::from_s24(self.clamping_scale(*sample, Self::SCALE_S24) as i32)), + ); + + output } pub fn f64_to_s16(&mut self, samples: &[f64]) -> Vec { - samples - .iter() - .map(|sample| self.scale(*sample, Self::SCALE_S16) as i16) - .collect() + let mut output = Vec::with_capacity(samples.len()); + + output.extend( + samples + .iter() + .map(|sample| self.scale(*sample, Self::SCALE_S16) as i16), + ); + + output } }