gnucash maint: [utilities] create general string-replace-substring

Christopher Lam clam at code.gnucash.org
Wed Apr 24 23:16:39 EDT 2019


Updated	 via  https://github.com/Gnucash/gnucash/commit/7d15e6e4 (commit)
	from  https://github.com/Gnucash/gnucash/commit/a12bbacc (commit)



commit 7d15e6e4e727c87fb4a501e924c4ae02276e508d
Author: Christopher Lam <christopher.lck at gmail.com>
Date:   Sun Apr 21 23:15:47 2019 +0800

    [utilities] create general string-replace-substring
    
    copied function created by Mark Weaver, core guile dev and augmented
    to selectively replace substring indices
    
    This is a much more efficient function than the previous
    gnc:substring-replace which will constantly split lists using
    substring, and create new strings using string-append.
    
    It also does tail call optimization properly, unlike the previous
    functions.
    
    https://lists.gnu.org/archive/html/guile-devel/2013-09/msg00029.html -
    original
    
    "Here's an implementation that does this benchmark about 80 times
    faster on my machine: (20 milliseconds vs 1.69 seconds)
    
    --8<---------------cut here---------------start------------->8---
    (define* (string-replace-substring s substr replacement
                                       #:optional
                                       (start 0)
                                       (end (string-length s)))
      (let ((substr-length (string-length substr)))
        (if (zero? substr-length)
            (error "string-replace-substring: empty substr")
            (let loop ((start start)
                       (pieces (list (substring s 0 start))))
              (let ((idx (string-contains s substr start end)))
                (if idx
                    (loop (+ idx substr-length)
                          (cons* replacement
                                 (substring s start idx)
                                 pieces))
                    (string-concatenate-reverse (cons (substring s start)
                                                      pieces))))))))
    --8<---------------cut here---------------end--------------->8---
    
    The reason this is so much faster is because it avoids needless
    generation of intermediate strings."



Summary of changes:
 libgnucash/scm/utilities.scm | 110 +++++++++++++++----------------------------
 1 file changed, 39 insertions(+), 71 deletions(-)



More information about the gnucash-patches mailing list