enum str = "abc"; vs string str = "abc";
H. S. Teoh
hsteoh at quickfur.ath.cx
Wed Jan 16 18:50:51 UTC 2019
On Wed, Jan 16, 2019 at 06:21:29PM +0000, Victor Porton via Digitalmars-d wrote:
> What is more space efficient:
>
> enum str = "safjkdfjksdlfkdsj";
>
> or
>
> string str = "safjkdfjksdlfkdsj";
>
> ?
>
> with the first code fragment, won't the string be re-created and
> re-inserted into the object file one time whenever str is used, rather
> than once?
Strings are a bit special, in that the compiler automatically stores
them in a string table and emits them only once. However, you're quite
right that using enum with arrays in general is not a good idea
space-wise.
> What of the two you would recommend?
Use:
immutable str = "...";
in module-global scope. Or if this is inside a function,
static immutable str = "...";
This places it in the data section of the object file and elides the
extra pointer/size pair of `str` if it were mutable.
OTOH, if `str` is only referenced at compile-time, then it's more
efficient to use the enum, because then it won't even appear in the
object file. :-) Also, you may have no choice but to use an enum if
`str` is referenced by compile-time code, since static globals would not
be readable at compile-time.
T
--
Study gravitation, it's a field with a lot of potential.
More information about the Digitalmars-d
mailing list