How the compiler manages the same char?

2019-09-24 08:06发布

问题:

I would like to know if the compiler (I'm using VS 2015) optimizes also if the same character is found when it checks the code?

Example:

wstrFile.find_last_of(L"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ");
wstrFile.find_last_of(L"aefgh");

"aefgh" (used two times) are stored once only somewhere when the program is started?

Otherwise, is it useful to store them in a variable to gain (a little bit) space? (in all cases, I will use this variable further)

回答1:

No, never.

The default and usual behaviour is that if you define a constant object of any kind (string, array, etc) then the compiler will allocate at least that amount of storage somewhere and set the contents as defined. Storage will usually be allocated on some kind of boundary, so very often a few bytes are wasted as padding.

Some compilers may optionally allocate a single string or other constant object even though you declare it more than once, but only at the level of complete objects, never (as you asked) individual characters within a string.

Most optimisation aims at getting programs to run faster, perhaps at the expense of more memory. Strategies to save a few bytes of storage have no worthwhile payoff and are not pursued.



回答2:

An implementation is permitted to make L"abcdef" and L"abcdef" have the same address, but it is impossible for one to make L"cd" point to the middle characters of that literal, because the literal must end with a NULL character, and no NULL character exists at that location in the original string.

Use cases where memory is extremely tight do exist, but I'd say on balance the likelihood of you needing to care about this is slim to none.