0

I am trying to improve the performance of my application. Currently, I have the following code in place which iterates more than 1000 times:

if(!condition){
    switch(const) {
          case one : value = x; break;  
          case two : value = y; break;
    }
} else {
    switch(const) {
          case one : value = p; break;  
          case two : value = q; break;
    }
}

If I refactor the code as follows will it improve performance?

switch(const) {
      case one : condition ? value = p : value = x; break;  
      case two : condition ? value = q : value = y; break;
}
Thomas Flinkow
  • 4,845
  • 5
  • 29
  • 65
DoctorAV
  • 1,189
  • 1
  • 14
  • 40
  • 1
    See [this](https://stackoverflow.com/a/395965/7571171) answer, it explains why `switch` should be preferred over `if`s in certain cases. Apart from that, it is very unlikely that this actually is a bottleneck of your application, so my advice would be go for what is more readable. – Thomas Flinkow Feb 28 '18 at 06:55
  • @RandomThoughts maybe look at **Task Parallel** library, if you iterate in separated threads, then you sure will improve the performance – Ferus7 Feb 28 '18 at 07:00
  • 2
    Have you run your program through a profiler so that you know this is a bottleneck? – Lasse V. Karlsen Feb 28 '18 at 07:10
  • @LasseVågsætherKarlsen yes I have, this is one of the bottleneck. I have other things too but just havn't find out workaround for them. – DoctorAV Feb 28 '18 at 07:15
  • 1
    Then just make a change, run profiler again and see if it helps (I doubt it will). – Evk Feb 28 '18 at 07:21
  • If const and one and two are in fact constant perhaps you can move the switch outside of the iteration? That way the inner loop will only need to check the condition and you can gain a few cycles. – ewramner Feb 28 '18 at 09:21

1 Answers1

0

you can record time using the stopwatch, so you can see your self but when I verified I see a performance improvement with a second logic. also, it may vary by a condition which your passing.

 System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();
             stopwatch.Start(); // START THE WATCH

            // write your logic here 

            stopwatch.Stop(); // STOP THE WATCH

            Console.WriteLine("Time taken : {0}", stopwatch.Elapsed);
            Console.ReadKey();

Hope it helps you.

  • Apart from `Stopwatch` not being very appropriate for this kind of (micro) benchmarks, this is not an answer. I haven't tested it, but due to `Stopwatch.Elapsed` being a `TimeSpan`, the smallest possible recorded time is milliseconds, and I believe the shown code differes only by a few nano- or milliseconds, so that `Stopwatch.Elapsed` would be `0` in both cases. – Thomas Flinkow Feb 28 '18 at 11:56