When programming, it can be wasteful to store the same constant data again and again. You use more memory, you access more data. Thankfully, your opti

Optimizing compilers deduplicate strings and arrays

submited by
Style Pass
2022-09-23 23:00:31

When programming, it can be wasteful to store the same constant data again and again. You use more memory, you access more data. Thankfully, your optimizing compiler may help.

There is redundancy since the prefix “Good day professor” is the same in both cases. To my knowledge, no compiler is likely to trim this redundancy. However, you can get the desired trimming by breaking the strings:

Most compilers will recognize the constant string and store it once in the program. It works even if the constant string “Good day professor” appears in different functions.

All compilers I tried return false. They create two C strings even if one is a prefix of the other in the following example…

Unsurprisingly, the “data compression” trick works with arrays. For example, the arrays in these two functions are likely to be compiled to just one array because the compiler recognizes that they are identical:

Of course, if you want to make sure to keep your code thin and efficient, you should not blindly rely on the compiler. Nevertheless, it is warranted to be slightly optimistic.

Leave a Comment