0
Creating new variable when using string function
Should I create a new variable whenever i use a string function since it makes a copy. Like: sentence = âtext text textâ sentence = sentence.split() or sentence = âtext text textâ new_sentence = sentence.split() The sentence itself never changed nothing new but i just split on space
5 Answers
+ 4
There is no absolute better. It depends on how you use the variable later on in your code. Strings are immutable, so you always have to create modified copies.
If you don't need to keep the original value, assigning to the same variable is more economical, since you are not creating new objects and you only have to deal with the original variable.
If other variables need to access the unmodified value, you must assign it to a new variable so that the original value is not changed.
+ 4
Your question is very general, without concrete example and programming language.
In any development it comes down to concrete case.
Generally it is tried to make a program as fast as possible, modular, reusable, use little memory, take a language that is most suitable in this case and find a compromise between benefits and costs or find a buyer.
0
is it better to create a new variable since i can modify the original string if i wanted
0
If you're talking about Python (which the code looks like), add a Python tag.
I read that Python garbage collection is an "implementation detail" so memory might or might not be recovered during run time when all references to an object are removed, depending on the implementation. However, memory is not allowed to be recovered by any implementation while there are still existing references to an object.
So, if you do this.
sentence = âtext text textâ
sentence = sentence.split()
The reference to "text text text" is removed, because sentence now refers to ["text", "text", "text"], and there's a chance that the implementation will recover the memory during runtime.
However, if you do this,
sentence = âtext text textâ
new_sentence = sentence.split()
The reference to "text text text" still exists, even if you never explicitly access it again, which means the memory cannot be recovered until your program ends.
So for memory management, reusing the same identifiers can be better in some implementations.