Created
July 27, 2018 01:53
-
-
Save jackmott/f61fe8dbe80f18ba2a6d35ecfc19c1f9 to your computer and use it in GitHub Desktop.
for vs foreach
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Diagnostics; | |
namespace ConsoleApp11 | |
{ | |
class Program | |
{ | |
static long count_for(int[] a1, int[] a2) | |
{ | |
long count = 0; | |
for (int i = 0; i < a1.Length; i++) | |
{ | |
for (int j = 0; j < a2.Length; j++) | |
{ | |
if (a1[i] + a2[j] % 3 == 0) | |
{ | |
count++; | |
} | |
} | |
} | |
return count; | |
} | |
static long count_foreach(int[] a1, int[] a2) | |
{ | |
long count = 0; | |
foreach (int a in a1) | |
{ | |
foreach (int b in a2) | |
{ | |
if (a + b % 3 == 0) | |
{ | |
count++; | |
} | |
} | |
} | |
return count; | |
} | |
static void Main(string[] args) | |
{ | |
int[] a1 = new int[20000]; | |
int[] b1 = new int[20000]; | |
for (int i = 0; i < a1.Length; i++) | |
{ | |
a1[i] = i; | |
b1[i] = i / 2; | |
} | |
var s = new Stopwatch(); | |
s.Start(); | |
long r_for = count_for(a1, b1); | |
s.Stop(); | |
Console.WriteLine("for loop took:" + s.ElapsedMilliseconds + " answer:" + r_for); | |
s.Restart(); | |
long r_foreach = count_foreach(a1, b1); | |
s.Stop(); | |
Console.WriteLine("foreach Took:" + s.ElapsedMilliseconds + " answer:" + r_foreach); | |
s.Restart(); | |
r_for = count_for(a1, b1); | |
s.Stop(); | |
Console.WriteLine("for loop Took:" + s.ElapsedMilliseconds + " answer:" + r_for); | |
s.Restart(); | |
r_foreach = count_foreach(a1, b1); | |
s.Stop(); | |
Console.WriteLine("foreach Took:" + s.ElapsedMilliseconds + " answer:" + r_foreach); | |
Console.ReadLine(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment