0

Here is an example. Suppose I want to split a string on multiple delimiters using the String.Split() method. Here's what I would write in C#:

    myString.Split(new [] { ',', ';', ':' }, StringSplitOptions.RemoveEmptyEntries)

Now, the actual argument to the function is an array of constant (i. e. known at the compile/JIT time) values, and this array is, at the least syntactically, allocated every time the expression is evaluated.

Is there a magic (or optimization, if you do not believe in magic) in the CLR that will avoid allocating and initializing the array every time, or is the array really constructed every time this code is executed? I am asking both in a broad sense about the CLR in general, if there is such a thing, and also narrowly about the Microsoft's implementation in .NET in particular.

1 Answer 1

1

No, the array will be allocated every time. Probably not a big deal in average situations, but could pretty well be in a tight loop, or if called very often (like on a busy server, etc.).

In summary, if you suffer here, it is best to put your typical delimiter arrays in a helper class, like so:

public static class SplitHelpers 
{
   public static readonly char[] Comma = { ',' };
   public static readonly char[] Stuff = { ',', ':', ';' };
   // etc.
}

Then use these from your call sites:

myString.Split(SplitHelpers.Stuff, StringSplitOptions.RemoveEmptyEntries)

Credit, where credit is due, Marc Gravell has written an pretty good blog post about this issue. I suggest you read that for more details.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.