Reenter Code and Local Variables

I have a method like:

private static string AmpRemove(string str) { int index = str.IndexOf('&'); if (index > 0) str = str.Substring(0, index); return str; } 

Here I am trying to get text from a string until the & character is found. My elder changed this method to

 private static string AmpRemove(string str) { if (str.IndexOf('&') > 0) str = str.Substring(0, str.IndexOf('&')); return str; } 

Therefore, instead of storing index he will calculate it twice, and his argument was that, since this method will be called in several threads, there may be an invalid value stored in index .

My understanding of the stream is limited, but I believe that each stream will have its own stack, where the str and index parameters will be set. I tried to reason with him that this is reentrant code, and there is no way for multiple threads to modify a local variable in this method.

So my question is: do I believe that caching saving index is the best solution, since it will not include calculating the index twice and since it is a local variable and str is a parameter local to the method, there is no way for multiple threads to change / change str and index ?

Is it correct?

+6
source share
2 answers

index cannot be changed based on code, because it is a local variable, and any method called from another thread is a separate call and, therefore, does not use local variables.

However, you do not control the string parameter, as it is passed. This will make it unsafe ... Except for MSDN , the string object is immutable. Thus, you can assume that the string you received remains unchanged between calls and is thread safe. Although you reassigned the value of str , the parameter was not passed as ref and therefore only reassigns the local pointer, it does not change the caller variable that was passed.

Thus, the first code presented is thread safe. Any changes to the type being transmitted or being transmitted to them cannot be immediately accepted in streaming mode.

+8
source

Your original method is thread safe. But:

  • Overriding method variables can be confusing, you can simply return a substring: private static string AmpRemove(string str) { var index = str.IndexOf('&'); if (index > 0) { return str.Substring(0, index); } return str; } private static string AmpRemove(string str) { var index = str.IndexOf('&'); if (index > 0) { return str.Substring(0, index); } return str; }

  • If '&' is at index 0, your code will return the entire string. Is this what should happen, or should index> = 0?

+2
source

Source: https://habr.com/ru/post/978156/


All Articles