📜 ⬆️ ⬇️

When to save the length of an array to a local variable in C #

While reading Habr, I came across the article “ Should I save the length of an array to a local variable in C #? ” (Which was in the “best” section). It seems to me a stupid question, not quite correct measurements (why are there no measurements for nested loops?) And a strange conclusion.

The length of the array in C # should be saved in a separate variable in the case when we have several nested loops, below is an example.

Here is a simple test code without saving the length of the array into a variable:

Random rnd1 = new Random(DateTime.UtcNow.Millisecond); int[,] arr1 = new int[Int16.MaxValue, Byte.MaxValue]; for (int i = 0; i < arr1.GetLength(0); i++) { for (int j = 0; j < arr1.GetLength(1); j++) { arr1[i, j] = rnd1.Next(Int32.MinValue, Int32.MaxValue); } } 

Here is the same code c preserving the length of the array into a variable:

 Random rnd1 = new Random(DateTime.UtcNow.Millisecond); int[,] arr1 = new int[Int16.MaxValue, Byte.MaxValue]; int len1 = arr1.GetLength(0), len2 = arr1.GetLength(1); for (int i = 0; i < len1; i++) { for (int j = 0; j < len2; j++) { arr1[i, j] = rnd1.Next(Int32.MinValue, Int32.MaxValue); } } 

Code with the preservation of the length of the array into a variable (the second option) is executed about 15% faster.

Such an answer can be found in more or less thick books on C # or .Net, but a smart person posts it on Habré and no one in the comments indicated to him that the length of the array in C # is saved to a variable, usually for nested loops, and there it really has meaning.

I just wanted to leave a comment there, but I could not register without registration, but after registration it turned out that after registration I could not leave a comment there (since more than 10 days had passed from the moment of publication). Maybe someone will notice this note and copy it there in the form of a comment or something like that.

Source: https://habr.com/ru/post/438516/