Warning: embarrassingly naive question
So of course I want my code to be DRY but whenever I try to tuck some String procesing logic into a function I am suddenly concerned about how it must now return a new String
allocation, whereas without the function I avoid a new allocation yet I suffer code duplication.
For instance, let's say I have some silly function in performance-critical code:
fn what_matters(slice: &str) -> String {
// in reality, more could be done by this function... just a small example...
slice[1..slice.len() - 1].to_string()
}
Everywhere I call what_matters
I do not own the String
, it is read from a file I am parsing. So I'd like to avoid allocating a String
, which I achieve by not using what_matters
.
However, sometimes I end up duplicating little String operations like this, and so I would have a cleaner development experience reusing what_matters
instead, but then aren't I then performing String allocations unnecessarily everywhere what_matters
is called?
It makes me wonder... should I invest in macros instead to avoid the allocation and yet still make my code DRY?:
macro_rules! what_matters {
($slice:expr) => {{
$slice[1..$slice.len() - 1].to_string()
}}
}
I know I should benchmark my code before getting all worried like this, but this comes up so frequently I wouldn't have time in each scenario to benchmark. I don't want to litter my code base with little bottleneck landmines if I can avoid it, so is there general truth to this and possible rules of thumb I should follow?