Posts Tagged ‘ String Builder ’

more String Manipulations

The String.Format Method

The String.Format Method is a string manipulation function.

This method performs manipulation easily through a placeholder, which has a numerical value, surrounded by curly braces, in the format of {n}. The number must be a non-negative zero-based number, which identifies the replacement value to use on its behalf. For example, the code:

returns ”Brand BMW Model 511”

This function takes the placeholder {0} and replaces it with the object passed into the function. The placeholders operate in numerical order, so the zero placeholder receives the first variable, the one placeholder receives the second variable, and so on. If we want to have a string with n placeholders, we would use {0}, {1}, {2},…{n}

It is important to note that if a placeholder is left out, the variable designated for that placeholder is ignored.

The string.Format method provides a way for you to insert argument strings and separators together, and also to specify display options for each argument individually.

Here you can find more info about the String Format Method.

Let.s look at another string manipulation:

The String Builder

Instead of using this (longer) line of code:

I used “+=” to get the same result:

In small applications this works pretty well. But in bigger applications you will see, that you have slow performance and you use up too much battery power. The reason is that when a string is declared and initialized it takes up a fixed area of the computer’s or in this case, the phone’s memory.

So if you concatenate a string and reassign it to contain a new value there is some “behind the scenes” work to be done to create a new space in memory large enough to hold the new length of the string. In order to have free memory, some free space needs to be found.

Garbage Collection takes place. In this example this is happening a hundred times.

That’s why in this scenario it is preferred to use an object that is built to handle concatenation tasks, the StringBuilder.

Running this gives you the same result, but it is way more efficient, because it doesn´t create new objects for each new value. Therefore it gives you a faster, a better performance.

 

To be continued…

%d bloggers like this: