Improve code performance in C#

Asked

Viewed 1,229 times

4

I’m doing some tests with some C# codes and during an analysis I realized that some high-peak problems happen when integer value conversions occur to string, in the vast majority the conversion happens so: classe.valor.ToString("0.0") is there any way to improve this type of conversion? Using string.Format("{0:0.00}", classe.valor) the peak got even higher reducing the performance of the application. It would have some alternative?

These conversions happen within a continuous function, which is updated every frame.

Not to post the entire code here values come from several classes so I will post only a few snippets of one of the classes, so I can apply to the others:

distancia.text = string.Concat(string.Format("{0:0.00}", distance.metros), " m");

 if (contar)
    {
        i -= Time.deltaTime;

        timeCount.text = i.ToString("0").Replace("0","Go");

        if (i < 0)
        {                
            contar = false;
        }
    }

checkpoint.text = string.Concat("Distance: ", string.Format("{0:0.00}", distance.metros), " m");

if (manager.count)
    {
      var valor = int.Parse(rota.metros.ToString("00"));
      _menuManager.ShowMenu(Menu);
      endPoints.text = string.Concat("distance: ", string.Format("{0:0.00}", rotaMaior.metros), " m");
    }
  • 1

    It’s hard to point out anything. Post the rest of the code, where exactly there is the peak, as you measured, anyway, give more details so we can help.

2 answers

5


Just looking at this excerpt has nothing that can be done to get significantly better results. I could tell you to do a formatting function of your own, but probably it would be less efficient. I could tell you to take it out that’s causing the problem, but you need it, you shouldn’t have used it for nothing.

Has a _menuManager.ShowMenu(Menu) weird there. It seems to be mixing UI with data processing, this shouldn’t happen, it’s bad software engineering. I would find a way to separate things better, and it may be that this method is causing the problem. He seems to me absurdly heavier than the rest of the operation.

You have to try to isolate the problem somehow, see exactly where the problem is, you can’t guess. Either make an on-site measurement or use a Profiling like the ones I indicated in that reply.

The method Concat() is quite efficient. And even if it were not, he would have no problems in this case since concatenation has few items.

This code may be called more times than necessary.

Other than that, only if there are other parts that could be causing this, maybe this is in a poorly assembled loop.

  • yes, it’s a UI element, with some other components like for example animations of transactions, it’s really a lot to post here, more to get a sense of "such" optimization that I’m doing, just changing the form of string concatenation Ex: TextBox.text = variavelString1 + variavelString2 for TextBox.text = string.Concat(variavelString1, variavelString2) already reducing high impacts, so I imagined that short solutions or simple tips would serve =), and I use the Profiling.

  • I find it strange because the compiler does just what you’re saying it did manually, so it’s not to make any difference. http://stackoverflow.com/q/10341188/221800

  • thanks for the tips.

  • If you use the Profiling should know where exactly is the more bottleneck, it would be good to put the results of Profiling in the question.

2

There are many things that can be done to make your code performance much better.

However, there are two things you really should do and refactoring in order to get the performance up quickly:

  1. Separate Processing Outputs: In your code is very mixed the processing of your calculations with output for its interface. I recommend removing everything and turning it all into a real object, closed for modification but open for extension. Apparently you’re using a kind of Timer, it must have event like * Timeelapsed* or something like that. Use it to update your interface, so this processing will be in a thread separate, isolating the main stream
  2. Improve the casting - type conversion - and handling of string of your code. These conversions are costly, especially if performed in loop. And manipulate strings is also costly, because they are immutable.

Some examples:

//distancia.text = string.Concat(string.Format("{0:0.00}", distance.metros), "m");
distancia.text = string.Format("{0:0.00} m", distance.metros); // Removido um Concat()

//checkpoint.text = string.Concat("Distance: ", string.Format("{0:0.00}", distance.metros), " m");
checkpoint.text = string.Format("Distance: {0:0.00} m", distance.metros); // Removido um Concat()

//endPoints.text = string.Concat("distance: ", string.Format("{0:0.00}", rotaMaior.metros), " m");
endPoints.text = string.Format("distance: {0:0.00} m", rotaMaior.metros); // Removido um Contac()

Use ternary operators:

//timeCount.text = i.ToString("0").Replace("0","Go");
timeCount.text = i > 0 ? i : "Go"; // Removido ToString() e Replace()

Reduction of casting:

//var valor = int.Parse(rota.metros.ToString("00")); // Qual o tipo desse rota.metros ?
var valor = rota.metros; //Não vi onde você usar esse 'valor'

And I agree with @Maniero, that _menuManager.ShowMenu(Menu) is strange in this place. If you can share more code, it will help us to help you more.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.