[Solved] Why when I run a method with multiple threads is slower?


There are a couple of reasons why your code can run slower in an MT enviroment:

  • Running code multithreaded adds management overhead compared to running single threaded. Normally you’d hope that the parallelization of the executed code will make up for it in the sense that the overall execution time goes down on a multi-core system at the possible expense of every thread taking the same time or a little longer if/when you manage to light up all cores.
  • You’re code is doing something that is essential a serial operation (scanning the directory) in parallel. If you’re hitting the same directory, the results are very likely cached by your OS, but you’re hitting up four directories. This means you’ll have to wait for the IO to finish for each one of them while the operations fall over each other. That’s not a good scenario for improved performance.

Running code multithreaded for performance reasons (as opposed to, say, running code multithreaded because you want your UI to be responsive at all times) only makes sense if there is no common choke point and the operations are completely independent. That’s not the case in your example, because the IO is the bottleneck and that can’t be efficiently parallelized on a normal computer because you’re dealing with disk latency. There are ways to improve the latency (faster disks or SSDs) but you’re still dealing with an operation that’s essentially serial.

solved Why when I run a method with multiple threads is slower?