From 3363c3ef65070046b6b00563cfb1ab90c67d94d1 Mon Sep 17 00:00:00 2001 From: JalonSolov Date: Sat, 1 May 2021 14:27:49 -0400 Subject: [PATCH] builtin.string: optimize replace() (#9955) --- vlib/builtin/string.v | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/vlib/builtin/string.v b/vlib/builtin/string.v index 412f27dc41..11dc7f01e8 100644 --- a/vlib/builtin/string.v +++ b/vlib/builtin/string.v @@ -275,12 +275,12 @@ pub fn (s string) replace_once(rep string, with string) string { // replace replaces all occurences of `rep` with the string passed in `with`. pub fn (s string) replace(rep string, with string) string { - if s.len == 0 || rep.len == 0 { + if s.len == 0 || rep.len == 0 || rep.len > s.len { return s.clone() } // TODO PERF Allocating ints is expensive. Should be a stack array // Get locations of all reps within this string - mut idxs := []int{} + mut idxs := []int{cap: s.len / rep.len} defer { unsafe { idxs.free() } }