Home > OS >  Time and Space Complexity Practice (for using array length property)
Time and Space Complexity Practice (for using array length property)

Time:09-13

I have an array

int[] array = new int[10]{...}

I need to use this array length in different places inside my program.

Is it good practice to get it in variable like

int n = array.Length

and use the variable n everywhere? Or I can simply use

array.Length

everywhere it is needed.. since it is simple one , not a big calculation ?

Is there any significant difference in terms of time and space taken between these two approach?

CodePudding user response:

Short Answer:

Accessing Array.Length will probably be as efficient as keeping a separate variable, and therefore it is not advisable as a general guideline.

Longer Answer:

As you can see in the Array.Length Property documentation, in the remarks section:

Retrieving the value of this property is an O(1) operation.

(emphasis is mine).

This means that when you call Array.Length there is no need to traverse the array and count the elements (which would be an O(n) operation).

Instead the array class is keeping track of the number of elements in an internal member or property, which is returned when you access Array.Length.

Therefore is it very likely that keeping a separate variable will perform very similarly to accessing Array.Length (the only difference is the need to reference the array instance, but I tend to believe it is negligable).

However - if you are concerned about performance issues and suspect it is a critical area - the only real answer is that you have to measure both options and find out.

  • Related