3

Consider this code:

$fullText = $beforeStore . $store . $afterStore;

If $store is big and one wants to optimize memory usage (memory_get_peak_usage), they will find that here they use thrice the memory needed to keep $store since $store . $afterStore is another value of that size (or bigger) as well as $beforeStore . $store . $afterStore. So to optimize, I used

$fullText = $beforeStore . $store;
unset($store);
$fullText = $fullText . $afterStore;

which gives only twice in terms of memory_get_peak_usage and the final state (memory_get_usage) is the same as the initial (I omit unseting $beforeStore and $afterStore here).

Is there some smart way to concatenate in this optimized manner but without writing 1+n lines of code where n is the number of concatenated strings? (or 2n if we want to unset each of the concatenated lines)

YakovL
  • 7,557
  • 12
  • 62
  • 102
  • Instead of concatenating strings you can create an array of referenes to the values and use that instead of `$fullText`. Do you actually need a single variable holding everything? – Al.G. Dec 22 '17 at 22:08
  • 1
    and BTW, `unset` doesn't remove the variable from memory, https://stackoverflow.com/a/584982/2595450 – Spoody Dec 22 '17 at 22:09
  • @Al.G. well, in this particular case yes, `$fullText` is put into a file afterwards – YakovL Dec 22 '17 at 22:10
  • 1
    In that case you can do a continuous `fputs`/`fwrite` loop with all the values and you won't need them in a single variable. – Al.G. Dec 22 '17 at 22:12
  • @MehdiBounya thanks, I'll check if that helps to optimize further – YakovL Dec 22 '17 at 22:12
  • @Al.G. you're right, that's an option, probably I'll use that, thanks – YakovL Dec 22 '17 at 22:13

1 Answers1

4

Use string interpolation instead of concatenation, so it doesn't need to create intermediate strings for the partial results.

$fullText = "{$beforeStore}{$store}{$afterStore}";
Barmar
  • 741,623
  • 53
  • 500
  • 612