best/proper way to declare constants ?
H. S. Teoh
hsteoh at quickfur.ath.cx
Thu Aug 5 01:14:26 UTC 2021
On Thu, Aug 05, 2021 at 12:47:06AM +0000, someone via Digitalmars-d-learn wrote:
> What are the pros/cons of the following approaches ?
1) If the constant is a POD (int, float, etc.), use:
enum myValue = ...;
2) If the constant is a string or some other array:
static immutable string myString = "...";
static immutable Data[] myData = [ ... ];
Unless you have a specific reason to, avoid using `enum` with string and
array literals, because they will trigger a memory allocation *at every
single reference to them*, which is probably not what you want.
enum myArray = [ 1, 2, 3 ];
...
int[] data = myArray; // allocates a new array
int[] data2 = myArray; // allocates another array
// they are separate arrays with the same contents
assert(data !is data2);
assert(data == data2);
// allocates a temporary array, does the comparison, then
// discards the temporary
if (data == myArray) ...
foreach (i; 0 .. 10) {
int[] input = getUserInput(...);
// allocates a new array at every single loop iteration
if (input == myArray) { ... }
}
Don't do this. Use static immutable for arrays and strings, use enum
only for PODs.
T
--
It's amazing how careful choice of punctuation can leave you hanging:
More information about the Digitalmars-d-learn
mailing list