mdgriffith / elm-optimize-level-2

BSD 3-Clause "New" or "Revised" License
128 stars 14 forks source link

Add replacement for String.repeat #79

Closed jfmengels closed 2 years ago

jfmengels commented 2 years ago

This is a replacement for String.repeat

Original

repeat : Int -> String -> String
repeat n chunk =
    repeatHelp n chunk ""

repeatHelp : Int -> String -> String -> String
repeatHelp n chunk result =
    if n <= 0 then
        result

    else
        repeatHelp (Bitwise.shiftRightBy 1 n) (chunk ++ chunk) <|
            if Bitwise.and n 1 == 0 then
                result

            else
                result ++ chunk

Replacement

The replacement is equivalent to the following Elm code:

repeat : Int -> String -> String
repeat n chunk =
    repeatHelp n chunk ""

repeatHelp : Int -> String -> String -> String
repeatHelp n chunk result =
    if n <= 0 then
        result

    else
        repeatHelp (Bitwise.shiftRightBy 1 n)
            (chunk ++ chunk ++ "")
            (if Bitwise.and n 1 == 0 then
                result

             else
                result ++ chunk ++ ""
            )

The main improvements are:

For this PR, I have slightly altered the replacement to

These don't seem to have a noticeable effect as far as I can tell, but it reduces the bundle size ever so slightly maybe. Let me know if you want me to use the "original version".

Results

Benchmark is run with elm-optimize-level-2.

Chrome: Screenshot from 2022-01-07 16-29-36

Firefox: Screenshot from 2022-01-07 16-29-14

Notes

String replacements seem to be disabled in all configurations for the tool and I'm not sure why. That also needs to change otherwise this replacement will not have any effect.