Creating new variable when using string function | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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

2nd Jul 2023, 4:00 AM
Junior
Junior - avatar
4 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.
2nd Jul 2023, 5:24 AM
Bob_Li
Bob_Li - avatar
+ 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.
2nd Jul 2023, 6:14 AM
JaScript
JaScript - avatar
0
is it better to create a new variable since i can modify the original string if i wanted
2nd Jul 2023, 4:14 AM
Junior
Junior - avatar
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.
19th Sep 2023, 1:06 AM
Rain
Rain - avatar