Is there any way I can make this C# code faster? [closed]

牧云@^-^@ 提交于 2019-12-02 05:17:48

Since your profiler tells you get_element is a bottleneck, and the method itself is coded very efficiently, you need to minimize the number of times this method is called.

Calling get_element repeatedly in a loop forces it to performs the same parsing job repeatedly:

for (int i = 0 ; i != n ; i++) {
    var element = get_element(i);
    ... // Do something with the element
}

You should be able to fix this problem by rewriting get_element as GetElements returning all elements as a collection, and then taking individual elements from the same collection in a loop:

var allElements = GetElements();
for (int i = 0 ; i != n ; i++) {
    var element = allElements[i];
    ... // Do something with the element
}

in most cases I only need one or two elements

In this case you could make a method that retrieves all required indexes at once - for example, by passing BitArray of required indexes.

Ok, second try. Discarding String.Split due to performance reasons, something like this should work much faster than your implementation:

//DISCLAIMER; typed in my cell phone, not tested. Sure it has bugs but you should get the idea.
public string get_element(int index)
{
     var buffer = new StringBuilder();
     var counter = -1;

     using (var enumerator = text_line.GetEnumerator())
     {
         while (enumerator.MoveNext())
         {
             if (enumerator.Current == x12_reader.element_delimiter)
             {
                 counter++;
             }
             else if (counter == index)
             {
                 buffer.Append(enumerator.Current);
             }
             else if (counter > index)
                 break;
        }
     }

     return buffer.ToString();
}

I'm not sure what you are doing exactly, but if I'm understanding your code correctly, wouldn't get element be simpler as follows?

public string get_Element(int index)
{
    var elements = line_text.Split(new[] { x12_reader.element_delimiter });

    if (index > elements.Length)
        return "";

    return elements[index];
}   
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!