Jump to content
  • Advertisement
Sign in to follow this  
nuclear123

array access question

This topic is 2760 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Advertisement

im curious as to if i have an array like below

int nums[23];

if element nums[23] takes longer to access then nums[3]?

I am having a hard time imagining a compiler that wouldn't produce identically efficient code for either or those. Also, nums[23] is not a valid way to access that array. 23 is outside the bounds.

Share this post


Link to post
Share on other sites
I don't think it would since it doesn't have to iterate through all of them. Also 23 isn't valid because an array of 23 starts at 0 and ends at 22, so actually you would be accessing 22 not 23.

Share this post


Link to post
Share on other sites
Array access is in O(1) time, meaning it takes a single call to access any one member of the array. The underlying mechanics of the"[ ]" (index operator) just takes the base address of the array (the address of array[0]) and then jumps ahead by (size of the array member type in bytes) * (index given). Example:

I have an array of 10 ints, (int myArray[10]; ), on 32 bit architecture that should be 4 bytes per int.

If I call myArray[5], the request processes as "give me what exists at the address (4*5) bytes later than myArray[0]".

The cpu doesn't need to check through every element of an array, which is why they're preferable for random-access usage. Something like a linked list would take longer to find the 23rd element than the 3rd, but if that's all greek to you then don't worry.

Short answer is "they all take the same amount of time".

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!