Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy is this faster on 64 bit than 32 bit?
    text
    copied!<p>I've been doing some performance testing, mainly so I can understand the difference between iterators and simple for loops. As part of this I created a simple set of tests and was then totally surprised by the results. For some methods, 64 bit was nearly 10 times faster than 32 bit.</p> <p>What I'm looking for is some explanation for why this is happening. </p> <p>[The answer below states this is due to 64 bit arithmetic in a 32 bit app. Changing the longs to ints results in good performance on 32 and 64 bit systems.]</p> <p>Here are the 3 methods in question.</p> <pre><code>private static long ForSumArray(long[] array) { var result = 0L; for (var i = 0L; i &lt; array.LongLength; i++) { result += array[i]; } return result; } private static long ForSumArray2(long[] array) { var length = array.LongLength; var result = 0L; for (var i = 0L; i &lt; length; i++) { result += array[i]; } return result; } private static long IterSumArray(long[] array) { var result = 0L; foreach (var entry in array) { result += entry; } return result; } </code></pre> <p>I have a simple test harness that tests this</p> <pre><code>var repeat = 10000; var arrayLength = 100000; var array = new long[arrayLength]; for (var i = 0; i &lt; arrayLength; i++) { array[i] = i; } Console.WriteLine("For: {0}", AverageRunTime(repeat, () =&gt; ForSumArray(array))); repeat = 100000; Console.WriteLine("For2: {0}", AverageRunTime(repeat, () =&gt; ForSumArray2(array))); Console.WriteLine("Iter: {0}", AverageRunTime(repeat, () =&gt; IterSumArray(array))); private static TimeSpan AverageRunTime(int count, Action method) { var stopwatch = new Stopwatch(); stopwatch.Start(); for (var i = 0; i &lt; count; i++) { method(); } stopwatch.Stop(); var average = stopwatch.Elapsed.Ticks / count; return new TimeSpan(average); } </code></pre> <p>When I run these, I get the following results:<br> 32 bit:</p> <pre>For: 00:00:00.0006080 For2: 00:00:00.0005694 Iter: 00:00:00.0001717</pre> <p>64 bit</p> <pre>For: 00:00:00.0007421 For2: 00:00:00.0000814 Iter: 00:00:00.0000818</pre> <p>The things I read from this are that using LongLength is slow. If I use array.Length, performance for the first for loop is pretty good in 64 bit, but not 32 bit.</p> <p>The other thing I read from this is that iterating over an array is as efficient as a for loop, and the code is much cleaner and easier to read!</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload