Article 61S2C CodeSOD: Tying Two Strings

CodeSOD: Tying Two Strings

by
Remy Porter
from The Daily WTF on (#61S2C)

Lets say you have a simple problem. You have a string variable, and you'd like to store that string in another variable. You have a vague understanding of string immutability and something about the way references work in C#, but you don't really understand any of that. So, what do you do?

Well, if you're Tina's co-worker, you do this:

expiresIn = $"{accessToken.ExpiresIn}"

Now, the "advantage" of this is that it creates a new string object. So expiresIn holds a reference to a different piece of memory than accessToken.ExpiresIn. Is that valuable? Not in this case. expiresIn is a local variable that goes out of scope well before accessToken does.

The worst part? This co-worker tends to do this by default when assigning strings to variables, even inside of loops, which means there are a lot of unnecessary string copies going on, and thus a lot of extra garbage collection. And in the end, for no real benefit.

otter-icon.png [Advertisement] Otter - Provision your servers automatically without ever needing to log-in to a command prompt. Get started today!
External Content
Source RSS or Atom Feed
Feed Location http://syndication.thedailywtf.com/TheDailyWtf
Feed Title The Daily WTF
Feed Link http://thedailywtf.com/
Reply 0 comments