Take the following method (written in Ruby but this question could be applied to most OO languages)
# Getter method which returns an alert
def alertView
_alertView = AlertView.new
_alertView.title = "This is the title"
_alertView.body = "This is the body of my alert"
_alertView
end
Suppose this method is called regularly throughout the lifecycle of an application. The title and body attribute strings would be instantiated as new objects each time.
To optimise this, we could do the following:
ALERT_TITLE = "This is the title"
ALERT_BODY = "This is the body of my alert"
# Getter method which returns an alert
def alertView
_alertView = AlertView.new
_alertView.title = ALERT_TITLE
_alertView.body = ALERT_BODY
_alertView
end
This way, the ALERT_TITLE and ALERT_BODY strings are only instantiated once, when the class is defined, and then reused throughout the application’s lifecycle.
My question is: is the second approach optimal? While it means less work for the garbage collector and probably more stable memory use, it would also mean that the application is taking more memory all the time, rather than freeing objects that are not currently required. I’m torn between applying this to all of the constant strings within my application or not applying this approach at all and defining each string as and when required.
A third approach would be to use class variables but the only advantage this offers over the second approach is that the variables are lazy-loaded.
# Getter method which returns an alert
def alertView
_alertView = AlertView.new
_alertView.title = @@alert_title ||= "This is the title"
_alertView.body = @@alert_body ||= "This is the body of my alert"
_alertView
end
The two variants above are not entirely equal. Observe:
When two variables are assigned the same constant, there still is just one instance of the string in memory. When you assign a literal string, every variable has its own instance in memory (this doesn’t apply to symbols, which you correctly noted in another comment). So, everything depends on what you want to achieve (or avoid), how many instances you create and so on.
If the question is really about strings, as in your example, I would say that you stop caring about efficiency and start caring about code readability, as all these are tiny tiny fractions of the memory available to your programs nowadays.
So, I’d advice to do whatever you consider cleaner, from programmer’s perspective.