Length Vs Count Vs Initialized Variable in C#
This test originated from having to loop over millions of records in an array in an application that requires everything be as fast as possible. It was stumbled upon by accident when I accidentally used a variable for a loop construct instead of the actual length property.
Every programmer typically writes looping constructs similar to:
1 2 3 4 5 6 7 8 9 |
for (int x=0; x < SomeArray.Length; x++) { //your code here } //OR for (int x=0; x < SomeList.Count; x++) { //your code here } |
But what happens if the loop was tweaked slightly? That is, instead of checking the Length or Count property every iteration, we instead checked a variable initialized to the size of the array or list?
1 2 3 4 5 |
int theLength = SomeArray.Length; //or int theLength = SomeList.Count; for (int x=0; x < theLength; x++) { //your code here } |
So that’s when this Curious Consultant started wondering what’s faster? Length Vs Count vs Initialized Variable in C# looping constructs.
Let’s check it out!
The Nuts and Bolts
To start with, two basic arrays of ints and strings were chosen as they’re easy to generate and provide us some simple constructs.
Next, I chose to create an array of Dictionary objects and a List of Dictionary objects. This would provide a little bit more sizeable memory operations.
Lastly, to balance things out, I chose to create a List of ints.
The code is written in Visual Studio 2017 targeting .Net Framework version 4.7.1 x64. The source code is available at the end of this blog so you can benchmark it on your own system.
In a nutshell, the code does the following:
- Creates the list, arrays, and dictionaries, pre-sizing them where possible so no timing operations are spent generating or increasing the size of said objects.
- Loops through each object twice: the first time with the Length or Count property; the second time using an int variable initialized to the size of the Array or List object.
Assumptions:
- No exception handling as no exceptions should occur
- The sizes of the arrays or list would not change through the loop
The exe file was run under Windows 10 Professional 64-bit with 16GB of memory.
The test was run for the following Array/List sizes:
- 500
- 80,000
- 6,000,000
- 30,000,000
Locked and Loaded!
These tests were run 3 times, with the average of the 3 runs calculated.
All times are indicated in seconds.milliseconds format. Lower numbers indicate faster run time performance.
Winners are highlighted in green; there are no points for second place.
The Results Speak for Themselves:
With two exceptions, using the variable initialized to the size won hands down in every instance.
|
Number of Items |
|||
|
500 |
80,000 |
6,000,000 |
30,000,000 |
int[] length |
00.0000024 |
00.0000898 |
00.0048867 |
00.0241620 |
int[] variable |
00.0000010 |
00.0000770 |
00.0040654 |
00.0205747 |
|
||||
string[] length |
00.0000006 |
00.0000645 |
00.0042335 |
00.0187586 |
string[] variable |
00.0000005 |
00.0000233 |
00.0017314 |
00.0086074 |
|
||||
Dictionary<string, DateTime>[] length |
00.0000007 |
00.0001147 |
00.0072403 |
00.0416102 |
Dictionary<string, DateTime>[] variable |
00.0000009 |
00.0001077 |
00.0044890 |
00.0186091 |
|
||||
List<int>() count |
00.0000005 |
00.0001996 |
00.0185924 |
00.0796033 |
List<int>() variable |
00.0000023 |
00.0001280 |
00.0091754 |
00.0411283 |
|
||||
List<Dictionary<string, DateTime>>() count |
00.0000097 |
00.0002217 |
00.0191115 |
00.0818092 |
List<Dictionary<string, DateTime>>() variable |
00.0000019 |
00.0001371 |
00.0099309 |
00.0472050 |
In Summary:
Up to 30 million records, the time differences aren’t significant enough for an every day user to notice.
However, if there’s a need or requirement to micro-optimize, squeezing out every last little microsecond possible, then that’s the way to go.
The Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 |
using System; using System.Collections.Generic; using System.Collections; using System.Collections.Concurrent; using System.Data; using System.Data.Sql; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Threading; using System.Diagnostics; namespace TestApplication { class Program { static void Main(string[] args) { DateTime end; DateTime start = DateTime.Now; Console.WriteLine("### Overall Start Time: " + start.ToLongTimeString()); Console.WriteLine(); TestCountLengthVsVariable(500); TestCountLengthVsVariable(80000); TestCountLengthVsVariable(6000000); TestCountLengthVsVariable(30000000); end = DateTime.Now; Console.WriteLine(); Console.WriteLine("### Overall End Time: " + end.ToLongTimeString()); Console.WriteLine("### Overall Run Time: " + (end - start)); Console.WriteLine(); Console.WriteLine("Hit Enter to Exit"); Console.ReadLine(); } //#################################################### //Compare the speed differences between array.length //or object.count properties vs a variable that's initialized to the size //before any looping starts. //We're assuming no exceptions. Multiple GC.Collect calls to free up memory. //Code from http://cc.davelozinski.com static void TestCountLengthVsVariable(int numberOfItemsInObject) { Console.WriteLine("######## " + System.Reflection.MethodBase.GetCurrentMethod().Name); Console.WriteLine("Number items to create: " + numberOfItemsInObject.ToString("#,##0")); Stopwatch sw = new Stopwatch(); DateTime end = DateTime.Now; DateTime start = DateTime.Now; //Array objects to test the .length property int[] ia = new int[numberOfItemsInObject]; string[] sa = new string[numberOfItemsInObject]; Dictionary<string, DateTime>[] da = new Dictionary<string, DateTime>[numberOfItemsInObject]; //Other objects to test the .count property List<int> li = new List<int>(numberOfItemsInObject); List<Dictionary<string, DateTime>> lc = new List<Dictionary<string, DateTime>>(numberOfItemsInObject); int lengthOrCount = 0; //Other vars used for assignments so we do something int i = 0; string s = String.Empty; Dictionary<string, DateTime> d = new Dictionary<string, DateTime>(); //Initialize the int and string arrays for (int x = 0; x < numberOfItemsInObject; x++) { ia[x] = x; sa[x] = (new Guid()).ToString(); } //Int Array Length Comparison Test Console.WriteLine("###########################################################"); Console.WriteLine("Starting int[] length test " + numberOfItemsInObject.ToString("#,##0") + " at: " + DateTime.Now.ToLongTimeString()); sw.Restart(); for (int x = 0; x < ia.Length; x++) { i = ia[x]; } sw.Stop(); Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Total records iterated: " + ia.Length.ToString("#,##0")); Console.WriteLine("Time to run: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); i = 0; Thread.Sleep(500); //Int Array Var Comparison Test Console.WriteLine("###########################################################"); Console.WriteLine("Starting int[] variable test " + numberOfItemsInObject.ToString("#,##0") + " at: " + DateTime.Now.ToLongTimeString()); sw.Restart(); lengthOrCount = ia.Length; for (int x = 0; x < lengthOrCount; x++) { i = ia[x]; } sw.Stop(); Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Total records iterated: " + lengthOrCount.ToString("#,##0")); Console.WriteLine("Time to run: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); Array.Clear(ia, 0, ia.Length); GC.Collect(); Console.WriteLine("###########################################################"); Console.WriteLine("############### Starting Next Two Contests ################"); Console.WriteLine("###########################################################"); Thread.Sleep(500); //String Array Length Comparison Test Console.WriteLine("###########################################################"); Console.WriteLine("Starting string[] length test " + numberOfItemsInObject.ToString("#,##0") + " at: " + DateTime.Now.ToLongTimeString()); sw.Restart(); for (int x = 0; x < sa.Length; x++) { s = sa[x]; } sw.Stop(); Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Total records iterated: " + sa.Length.ToString("#,##0")); Console.WriteLine("Time to run: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); Thread.Sleep(500); //String Array Var Comparison Test Console.WriteLine("###########################################################"); Console.WriteLine("Starting string[] variable test " + numberOfItemsInObject.ToString("#,##0") + " at: " + DateTime.Now.ToLongTimeString()); sw.Restart(); lengthOrCount = sa.Length; for (int x = 0; x < lengthOrCount; x++) { s = sa[x]; } sw.Stop(); Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Total records iterated: " + lengthOrCount.ToString("#,##0")); Console.WriteLine("Time to run: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); Array.Clear(sa, 0, sa.Length); GC.Collect(); Console.WriteLine("###########################################################"); Console.WriteLine("############### Starting Next Two Contests ################"); Console.WriteLine("###########################################################"); //Done here to help prevent 'out of memory' errors for (int x = 0; x < numberOfItemsInObject; x++) { da[x] = new Dictionary<string, DateTime>(4); //To vary the sizes of the dictionaries added: for (int y = 0; y < numberOfItemsInObject % 5; y++) { da[x].Add((new Guid()).ToString(), DateTime.Now); } } //Dictionary Array Length Comparison Test Console.WriteLine("###########################################################"); Console.WriteLine("Starting Dictionary<string, DateTime>[] length test " + numberOfItemsInObject.ToString("#,##0") + " at: " + DateTime.Now.ToLongTimeString()); sw.Restart(); for (int x = 0; x < da.Length; x++) { d = da[x]; } sw.Stop(); Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Total records iterated: " + da.Length.ToString("#,##0")); Console.WriteLine("Time to run: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); d.Clear(); GC.Collect(); Thread.Sleep(500); //Dictionary Array Var Comparison Test Console.WriteLine("###########################################################"); Console.WriteLine("Starting Dictionary<string, DateTime>[] variable test " + numberOfItemsInObject.ToString("#,##0") + " at: " + DateTime.Now.ToLongTimeString()); sw.Restart(); lengthOrCount = da.Length; for (int x = 0; x < lengthOrCount; x++) { d = da[x]; } sw.Stop(); Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Total records iterated: " + lengthOrCount.ToString("#,##0")); Console.WriteLine("Time to run: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); d.Clear(); for (int x = 0; x < numberOfItemsInObject; x++) da[x].Clear(); Array.Clear(da, 0, da.Length); GC.Collect(); Thread.Sleep(500); Console.WriteLine("###########################################################"); Console.WriteLine("############### Starting Next Two Contests ################"); Console.WriteLine("###########################################################"); //Initialize the arrays. Done here to help alleviate out-of-memory errors for (int x = 0; x < numberOfItemsInObject; x++) { li.Add(x); } //List Count Comparison Test Console.WriteLine("###########################################################"); Console.WriteLine("Starting List<int>() count test " + numberOfItemsInObject.ToString("#,##0") + " at: " + DateTime.Now.ToLongTimeString()); sw.Restart(); for (int x = 0; x < lc.Count; x++) { i = li[x]; } sw.Stop(); Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Total records iterated: " + li.Count.ToString("#,##0")); Console.WriteLine("Time to run: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); Thread.Sleep(500); //List Var Comparison Test Console.WriteLine("###########################################################"); Console.WriteLine("Starting List<int>() variable test " + numberOfItemsInObject.ToString("#,##0") + " at: " + DateTime.Now.ToLongTimeString()); sw.Restart(); lengthOrCount = li.Count; for (int x = 0; x < lengthOrCount; x++) { i = li[x]; } sw.Stop(); Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Total records iterated: " + lengthOrCount.ToString("#,##0")); Console.WriteLine("Time to run: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); li.Clear(); GC.Collect(); Thread.Sleep(500); Console.WriteLine("###########################################################"); Console.WriteLine("############### Starting Next Two Contests ################"); Console.WriteLine("###########################################################"); //Initialize the arrays. Done here to help alleviate out-of-memory errors for (int x = 0; x < numberOfItemsInObject; x++) { lc.Add(new Dictionary<string, DateTime>(4)); //To vary the sizes of the dictionaries added: for (int y = 0; y < numberOfItemsInObject % 5; y++) { lc[x].Add((new Guid()).ToString(), DateTime.Now); } } //List Count Comparison Test Console.WriteLine("###########################################################"); Console.WriteLine("Starting List<Dictionary<string, DateTime>>() count test " + numberOfItemsInObject.ToString("#,##0") + " at: " + DateTime.Now.ToLongTimeString()); sw.Restart(); for (int x = 0; x < lc.Count; x++) { d = lc[x]; } sw.Stop(); Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Total records iterated: " + lc.Count.ToString("#,##0")); Console.WriteLine("Time to run: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); d.Clear(); GC.Collect(); Thread.Sleep(500); //List Var Comparison Test Console.WriteLine("###########################################################"); Console.WriteLine("Starting List<Dictionary<string, DateTime>>() variable test " + numberOfItemsInObject.ToString("#,##0") + " at: " + DateTime.Now.ToLongTimeString()); sw.Restart(); lengthOrCount = lc.Count; for (int x = 0; x < lengthOrCount; x++) { d = lc[x]; } sw.Stop(); Console.WriteLine("Finished at: " + DateTime.Now.ToLongTimeString()); Console.WriteLine("Total records iterated: " + lengthOrCount.ToString("#,##0")); Console.WriteLine("Time to run: " + sw.Elapsed.ToString("mm\\:ss\\.fffffff")); d.Clear(); for (int x = 0; x < numberOfItemsInObject; x++) lc[x].Clear(); lc.Clear(); GC.Collect(); //cleanup whatever's left ia = null; sa = null; da = null; li = null; lc = null; Console.WriteLine(); } } //class } //namespace |