In some languages it is possible for the developer to specify an initial size for a string. Has Raku something similar? I have a string where I'll be concatenating text a few thousand times. The final size can be calculated before creating the string. I would like to test if I can save a few 100ms with this.
Short answer: No.
Longer answer: when you concatenate strings in Rakudo on the MoarVM backend, you don't actually create a concatenated string: internally, you have an object that consists of the separate pieces of strings.
There is only one case where the string actually gets concatenated: and that's when you use it as a haystack in a regular expression. And I believe there's a maximum number of "pieces" of string that, when reached, will cause actual concatenation in memory.
If you're looking at optimization: then don't concatenate each time, but push to a native str
array, and when done, then .join
that:
my str @parts;
while $todo {
@parts.push: "foo";
}
@parts.join
This is generally faster because a. you're using native strings, and b. all of the concatenation logic (which is actually not as simple as you think because e.g. a diacritic codepoint can be at the start of a part, and that needs to possibly be joined with the last codepoint of the previous part) can be done in the VM without needing to switch between HLL ops and C-code of the VM.