Follow-up to “Simple String template replacement in Scala and Clojure”

后端 未结 3 1838
臣服心动
臣服心动 2021-01-22 00:27

In my previous post, I showed a simple (naive) algorithm for doing a String template replacement.

One of the solutions, provided by mikera, seems like a much better algo

3条回答
  •  半阙折子戏
    2021-01-22 01:19

    I've written some Clojure code ( https://gist.github.com/3729307 ) that allows to interpolate any map value into a template, in probably the fastest possible way (see below) IF the template is known at compile-time.

    It doesn't use the same template syntax (although it could be adapted for that), but I think it still can be used to solve the exact same problem.

    With this solution, the code would have to be rewritten like...

    ; renderer-fn is defined in https://gist.github.com/3729307
    (time (dotimes [n 100] ((renderer-fn
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Pellentesque
    elit nisi, egestas et tincidunt eget, " (:foo %) " mattis non erat. Aenean ut
    elit in odio vehicula facilisis. Vestibulum quis elit vel nulla
    interdum facilisis ut eu sapien. Nullam cursus fermentum
    sollicitudin. Donec non congue augue. " (:bar %) " Vestibulum et magna quis
    arcu ultricies consectetur auctor vitae urna. Fusce hendrerit
    facilisis volutpat. Ut lectus augue, mattis " (:baz %) " venenatis " (:foo %)
    "lobortis sed, varius eu massa. Ut sit amet nunc quis velit hendrerit
    bibendum in eget nibh. Cras blandit nibh in odio suscipit eget aliquet
    tortor placerat. In tempor ullamcorper mi. Quisque egestas, metus eu
    venenatis pulvinar, sem urna blandit mi, in lobortis augue sem ut
    dolor. Sed in " (:bar %) " neque sapien, vitae lacinia arcu. Phasellus mollis
    blandit commodo.") {:foo "HELLO" :bar "GOODBYE" :baz "FORTY-TWO"})))
    
    ; => "Elapsed time: 1.371 msecs"
    

提交回复
热议问题