system
Given the following post, respond as if you're commenting on Reddit:
human
Why is accessing some random element near the start of an array FASTER than accessing a random element near the end?

I know they are both O(1) complexity, i'm talking at the hardware level here.

I know the difference is also very, very, very small.

Just recently I was doing a leetcode challenge one of which was a solution where lots of random access is done near the end of a 2D array. I found doing the exact same solution except from the front was \~10-20 ms faster and i'm talking consistently faster. This was in C++ with vectors

I then setup a test in python, and initialised an array of size 1 million, with random elements. I timed random element acccess near both the front and back, and the front of the array consistently produced faster results. I made sure the access was random to eliminate the compilers ability to optimise via caching etc.

Why would this be? I have always had the assumption accessing anywhere in memory should be roughly consistent.

Thanks for any input. Happy to share code if requested.
gpt
The vector itself has some metadata, such as total extent, bucket size, and an array of said buckets(buffers), and this metadata is allocated near the start of the memory block.  So, you access a vector, it has to touch the metadata (object properties) first, then access the proper place in memory.  Elements near the start are already in the L1 cache since the object header was just accessed.  Elements near the end are on different pages / different places in the RAM bus, the mother board's memory controller typically has a RAM cache too.

TL;DR: Similar place in memory accessed twice is faster than two vastly different pages of memory accessed in succession.