1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

string: optimize replace()

This commit is contained in:
Alexander Medvednikov 2019-12-10 18:50:21 +03:00
parent 6d5e9f88f8
commit 9726e18c0a

View File

@ -145,14 +145,14 @@ pub fn (s string) replace(rep, with string) string {
// TODO PERF Allocating ints is expensive. Should be a stack array // TODO PERF Allocating ints is expensive. Should be a stack array
// Get locations of all reps within this string // Get locations of all reps within this string
mut idxs := []int mut idxs := []int
mut rem := s mut idx := 0
mut rstart := 0
for { for {
mut i := rem.index(rep) or { break } idx = s.index_after(rep, idx)
idxs << rstart + i if idx == -1 {
i += rep.len break
rstart += i }
rem = rem.substr(i, rem.len) idxs << idx
idx++
} }
// Dont change the string if there's nothing to replace // Dont change the string if there's nothing to replace
if idxs.len == 0 { if idxs.len == 0 {