Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are foreach and the use of collections slow?

I'm refactoring my app to make it faster. I was looking for tips on doing so, and found this statement:

"ForEach can simplify the code in a For loop but it is a heavy object and is slower than a loop written using For."

Is that true? If it was true when it was written, is it still true today, or has foreach itself been refactored to improve performance?

I have the same question about this tip from the same source:

"Where possible use arrays instead of collections. Arrays are normally more efficient especially for value types. Also, initialize collections to their required size when possible."

UPDATE

I was looking for performance tips because I had a database operation that was taking several seconds.

I have found that the "using" statement is a time hog.

I completely solved my performance problem by reversing the for loop and the "using" (of course, refactoring was necessary for this to work).

The slower-than-molasses code was:

for (int i = 1; i <= googlePlex; i++) {
    . . .
    using (OracleCommand ocmd = new OracleCommand(insert, oc)) {
    . . .
    InsertRecord();
    . . .

The faster-than-a-speeding-bullet code is:

using (OracleCommand ocmd = new OracleCommand(insert, oc)) {
    for (int i = 1; i <= googlePlex; i++) {
        . . .
        InsertRecord();
        . . .
like image 458
B. Clay Shannon-B. Crow Raven Avatar asked Nov 29 '22 14:11

B. Clay Shannon-B. Crow Raven


2 Answers

Short answer:

Code that is hard to read eventually results in software that behaves and performs poorly.

Long answer:

There was a culture of micro-optimization suggestions in early .NET. Partly it was because a few Microsoft's internal tools (such as FxCop) had gained popularity among general public. Partly it was because C# had and has aspirations to be a successor to assembly, C, and C++ regarding the unhindered access to raw hardware performance in the few hottest code paths of a performance critical application. This does require more knowledge and discipline than a typical application, of course. The consequences of performance related decisions in framework code and in app code are also quite different.

The net impact of this on C# coding culture has been positive, of course; but it would be ridiculous to stop using foreach or is or "" just in order to save a couple CIL instructions that your recent jitter could probably optimize away completely if it wanted to.

There are probably very many loops in your app and probably at most one of them might be a current performance bottleneck. "Optimizing" a non-bottleck for perfomance at the expense of readability is a very bad deal.

like image 196
Jirka Hanika Avatar answered Dec 04 '22 11:12

Jirka Hanika


It's true in many cases that foreach is slower than an equivalent for. It's also true that

for (int i = 0; i < myCollection.Length; i++) // Compiler must re-evaluate getter because value may have changed

is slower than

int max = myCollection.Length;
for (int i = 0; i < max; i++) 

But that probably will not matter at all. For a very detailed discussion see Performance difference for control structures 'for' and 'foreach' in C#

Have you done any profiling to determine the hot spots of your application? I would be astonished if the loop management overhead is where you should be focusing your attention.

like image 33
Eric J. Avatar answered Dec 04 '22 10:12

Eric J.