Fastest way to read/store lots of multidimensional data? (Java)

前端 未结 5 1402
萌比男神i
萌比男神i 2021-01-02 18:14

I have three questions about three nested loops:

for (int x=0; x<400; x++)
{
    for (int y=0; y<300; y++)
    {
        for (int z=0; z<400; z++)
          


        
5条回答
  •  一个人的身影
    2021-01-02 18:42

    I would guess that this has alot to do with caching and registers and the principle of memory locality.

    Java has to access thousands of more bytes of memory when storing into an array. With the single variable, it can just keep that value in the cache and just keep updating it.

    The cache isn't large enough to hold the whole multi-dimensional array, so Java has to keep updating the cache to and from memory. Cache access times are way faster than memory access times.

    I don't even see why you would do this test though. If you need to store lots of data in a multi-dimensional array, using a single variable isn't helpful, even if it is faster.

    Also, the reason that when the parameters are switched around when accessing the array is because you are jumping around in memory a lot more (lots more cache misses) than when you are just iterating the other way.

提交回复
热议问题