Amandeep kaur
Amandeep kaur

Reputation: 1025

Does defining a constant consume some memory?

I am using Go to build an application.

I need to define a lot of constants for architectural purpose. Like we have a section named posts and I want to perform some action on it. Its log will be saved in the system with type posts.

Problem

I have around 50 sections like this. And for ease of use of section type I wanted to define section types as constants. But Like variables consumes some space in Go, do the constants too? Should I define them like this for multi purpose or refer the type everywhere with posts string.

What should I follow for my requirement?

Upvotes: 0

Views: 583

Answers (1)

Jonathan Hall
Jonathan Hall

Reputation: 79704

Does defining a constant consume some memory?

No.

And yes. Er, sort of, but not really.

Constants are a compile-time concept in Go. That means they don't actually exist while the program is running, so in that sense, no, they don't use memory.

However, typically constants don't exist in a vacuum. They're typically used somewhere in your code. For example:

const defaultName = "Unnamed"

/* then later */
var name = defaultName

Now the variable name is using memory, and it is assigned a value from the constant defaultName. So the constant, itself, is not using memory, per se, but the thing referencing the constant uses memory. You could also create many (potentially thousands or more) variables that all refer to the same constant, and would thus use many times more memory.

Generally, you can imagine that every constant is replaced with its literal value. If that literal value would "consume memory", then memory is consumed.

That is, this is equivalent to the above code snippet:

var name = "Unnamed"

So, the constant uses (or doesn't) the same memory that a literal value uses (or doesn't).

Upvotes: 5

Related Questions