Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

efficiently concatenate array of strings

The OCaml standard library provides the function String.concat

https://caml.inria.fr/pub/docs/manual-ocaml/libref/String.html

val concat : string -> string list -> string

String.concat sep sl concatenates the list of strings sl, inserting the separator string sep between each.

Presumably this function exists to make easier to concatenate many strings together in time/space linear in the length of the strings.

Does similar functionality exist for arrays? In particular, is there a way to efficiently concatenate an array of strings together without either 1) writing a C extension and building a tricky intermediate structure or 2) effectively calling String.concat "" (Array.to_list arr)).

like image 605
Gregory Nisbet Avatar asked Jan 18 '26 05:01

Gregory Nisbet


2 Answers

The best is to write your own concat function imitating String.concat. If you want something shorter, use a buffer to accumulate the result of your result (Array.iter (Buffer.add_string b) arr) — do not do repeated concatenations which will generate too many allocations.

like image 157
ChriS Avatar answered Jan 19 '26 19:01

ChriS


I'm sure there are more efficient ways of doing it, like the unsafe_blit approach String.concat is using, but a simple fold is at least an improvement over option 2:

Array.fold_left (fun acc s -> acc ^ s) "" arr

Reason/BuckleScript benchmark

like image 35
glennsl Avatar answered Jan 19 '26 19:01

glennsl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!