From 96297d3692e438fdd750aba04ea7dcd69bd06cbf Mon Sep 17 00:00:00 2001 From: Isaac Garzon Date: Tue, 27 Dec 2016 14:15:28 +0200 Subject: [PATCH] Improve performance for long strings by preallocating the needed memory --- src/lib.rs | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index c4a96c6..7f52ac3 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -13,17 +13,21 @@ pub fn left_pad(s: &str, pad: usize) -> String /// If str.len() is not less than pad, then the string is returned verbatim pub fn left_pad_char(s: &str, pad: usize, padchar: char) -> String { - let mut out = String::new(); - let len = s.len(); if pad > len { - for _ in 0..pad-len { + let left_pad = pad - len; + let capacity = s.len() + left_pad * padchar.len_utf8(); + let mut out = String::with_capacity(capacity); + + for _ in 0..left_pad { out.push(padchar); } - } - out.push_str(s); + out.push_str(s); - out + out + } else { + s.to_owned() + } } #[cfg(test)]