Improve the performance of a method with pointers

-4

Here's the code working:

string string_pick(string text, string tag, char caractere)
{
    int index = text.IndexOf(tag);
    return text.Substring(index + tag.Length, text.IndexOf(caractere, index + tag.Length + 1) - (index + tag.Length));
}

Example of operation:

string x = "kkkkkkkkkkkk jjjjjjjjjjj oloco icaro alguma coisa algumas palavras várias loucuras name:'icaro' lalala huhuasd sdiufhidf sdifuhisuhdf kkkkkkk";
string temporaria = string_pick(x,"name:'",'\'');

Temporary will be icaro.

Well, as you're going to mess with a gigantic string, I'd like to just access that part of memory and not copy the string again (in case the function's argument0 is doing).

In C ++ I solved it like this:

string string_pick(string *text, string tag, char caractere)
{
    int index = (*text).find(tag);
    return (*text).substr(index + tag.length(), (*text).find(caractere, index + tag.length() + 1) - (index + tag.length()));
}
    
asked by anonymous 17.06.2016 / 01:20

1 answer

3

First of all do crazy things that "work" is not programming. To do what is right is to program. Running is not a parameter to know if it's right. I will not say whether this is right or not because there is not enough information for this.

Even if it were possible to put the pointer in C # (even exists as, but in very specific situations that is not worth talking about here) doing what you are trying would not solve anything to save memory since inside the method is already creating a new instance . If there is any memory consumption problem, and even this is questionable, it is within the method and not in its communication with the outside world that it only copies the reference and is very efficient.

If the class StringBuilder could be a solution. But the case does not even show a real problem of performance or excessive allocation. And if you have the question should demonstrate. And you should only worry about this if the problem is real and not just an assumption.

The code written in C ++ is not even more efficient than the one written in C #. Alias is a complete unnecessary use pointer there. It's just creating meaningless indirection. You're probably crediting a quality to the pointer that it does not have.

The code can be simplified and have a better nomenclature . You can start by using the name in the StringPick() pattern. The names of the parameters could better indicate their function there, not only tell what they will have in it, this type already says.

Just to give an idea of what can be improved . I would do better if I knew the real requirements.

    
17.06.2016 / 02:08