Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory usage of concatenating strings using interpolated vs "+" operator

I see the benefit of using interpolated strings, in terms of readability:

string myString = $"Hello { person.FirstName } { person.LastName }!" 

over a concatenation done this way:

string myString = "Hello " + person.FirstName + " " person.LastName + "!"; 

The author of this video tutorial claims that the first one makes better use of memory.

How come?

like image 899
harveyAJ Avatar asked Feb 21 '17 14:02

harveyAJ


People also ask

What is the difference between string concatenation and interpolation?

Concatenation allows you to combine to strings together and it only works on two strings. Swift uses string interpolation to include the name of a constant or variable as a placeholder in a longer string, and to prompt Swift to replace it with the current value of that constant or variable.

What is the best way to concatenate strings in C #?

In C, the strcat() function is used to concatenate two strings. It concatenates one string (the source) to the end of another string (the destination). The pointer of the source string is appended to the end of the destination string, thus concatenating both strings.

Is string concatenation slow?

Each time strcat calls, the loop will run from start to finish; the longer the string, the longer the loop runs. Until the string is extensive, the string addition takes place very heavy and slow.


1 Answers

The author doesn't actually say that one makes better use of memory than the other. It says that the one method "makes good use of memory" in the abstract, which, by itself, doesn't really mean much of anything.

But regardless of what they said, the two methods aren't going to be meaningfully different in their implementation. Neither is going to be meaningfully different from the other in terms of memory or time.

like image 124
Servy Avatar answered Oct 30 '22 06:10

Servy