Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does String.ToLower() always allocate memory?

Does String.ToLower() return the same reference (e.g. without allocating any new memory) if all the characters are already lower-case?

Memory allocation is cheap, but running a quick check on zillions of short strings is even cheaper. Most of the time the input I'm working with is already lower-case, but I want to make it that way if it isn't.

I'm working with C# / .NET in particular, but my curiosity extends to other languages so feel free to answer for your favorite one!

NOTE: Strings are immutable but that does not mean a function always has to return a new one, rather it means nothing can change their character content.

like image 527
Neil C. Obremski Avatar asked Feb 02 '09 21:02

Neil C. Obremski


2 Answers

I expect so, yes. A quick test agrees (but this is not evidence):

string a = "abc", b = a.ToLower();
bool areSame = ReferenceEquals(a, b); // false

In general, try to work with comparers that do what you want. For example, if you want a case-insensitive dictionary, use one:

var lookup = new Dictionary<string, int>(
    StringComparer.InvariantCultureIgnoreCase);

Likewise:

bool ciEqual = string.Equals("abc", "ABC",
    StringComparison.InvariantCultureIgnoreCase);
like image 147
Marc Gravell Avatar answered Sep 19 '22 03:09

Marc Gravell


String is an immutable. String.ToLower() will always return new instance thereby generating another instance on every ToLower() call.

like image 27
cgreeno Avatar answered Sep 19 '22 03:09

cgreeno