Skip to content

Commit 9bdc5c8

Browse files
yoshi-monsterlpil
authored andcommitted
improve performance of string.join
1 parent af9dc54 commit 9bdc5c8

File tree

3 files changed

+18
-16
lines changed

3 files changed

+18
-16
lines changed

CHANGELOG.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@
44

55
- The `debug` function in the `io` module has been deprecated in favour of
66
the `echo` keyword.
7-
- The performance of `string.append` and `string.concat` have been improved.
7+
- The performance of `string.append`, `string.join`, and `string.concat` have
8+
been improved.
89

910
## v0.58.0 - 2025-03-23
1011

src/gleam/string.gleam

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -432,11 +432,23 @@ fn repeat_loop(string: String, times: Int, acc: String) -> String {
432432
/// // -> "home/evan/Desktop"
433433
/// ```
434434
///
435-
@external(javascript, "../gleam_stdlib.mjs", "join")
436435
pub fn join(strings: List(String), with separator: String) -> String {
437-
strings
438-
|> list.intersperse(with: separator)
439-
|> concat
436+
case strings {
437+
[] -> ""
438+
[first, ..rest] -> do_join(rest, separator, first)
439+
}
440+
}
441+
442+
fn do_join(
443+
strings: List(String),
444+
separator: String,
445+
accumulator: String,
446+
) -> String {
447+
case strings {
448+
[] -> accumulator
449+
[string, ..strings] ->
450+
do_join(strings, separator, accumulator <> separator <> string)
451+
}
440452
}
441453

442454
/// Pads the start of a `String` until it has a given length.

src/gleam_stdlib.mjs

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -205,17 +205,6 @@ export function split(xs, pattern) {
205205
return List.fromArray(xs.split(pattern));
206206
}
207207

208-
export function join(xs, separator) {
209-
const iterator = xs[Symbol.iterator]();
210-
let result = iterator.next().value || "";
211-
let current = iterator.next();
212-
while (!current.done) {
213-
result = result + separator + current.value;
214-
current = iterator.next();
215-
}
216-
return result;
217-
}
218-
219208
export function concat(xs) {
220209
let result = "";
221210
for (const x of xs) {

0 commit comments

Comments
 (0)