Skip to content

Improve performance of string.repeat #845

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
# Changelog

- The performance of the `string.repeat` function has been improved. It now runs
in loglinear time.

## v0.62.1 - 2025-08-07

- `string.inspect` now shows Erlang atoms as `atom.create("value")`, to match
Expand Down
21 changes: 17 additions & 4 deletions src/gleam/string.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,7 @@ fn concat_loop(strings: List(String), accumulator: String) -> String {

/// Creates a new `String` by repeating a `String` a given number of times.
///
/// This function runs in linear time.
/// This function runs in loglinear time.
///
/// ## Examples
///
Expand All @@ -416,13 +416,26 @@ fn concat_loop(strings: List(String), accumulator: String) -> String {
/// ```
///
pub fn repeat(string: String, times times: Int) -> String {
repeat_loop(string, times, "")
case times <= 0 {
True -> ""
False -> repeat_loop(string, times, string, "")
}
}

fn repeat_loop(string: String, times: Int, acc: String) -> String {
fn repeat_loop(
string: String,
times: Int,
doubling_acc: String,
acc: String,
) -> String {
let acc = case times % 2 {
0 -> acc
_ -> acc <> doubling_acc
}
let times = times / 2
case times <= 0 {
True -> acc
False -> repeat_loop(string, times - 1, acc <> string)
False -> repeat_loop(string, times, doubling_acc <> doubling_acc, acc)
}
}

Expand Down
6 changes: 6 additions & 0 deletions test/gleam/string_test.gleam
Original file line number Diff line number Diff line change
Expand Up @@ -106,8 +106,14 @@ pub fn concat_emoji_test() {
}

pub fn repeat_test() {
assert string.repeat("hi", times: 1) == "hi"

assert string.repeat("hi", times: 2) == "hihi"

assert string.repeat("hi", times: 3) == "hihihi"

assert string.repeat("a", times: 10_001) |> string.length == 10_001

assert string.repeat("hi", 0) == ""

assert string.repeat("hi", -1) == ""
Expand Down