The fastest way to iterate through a collection of objects

Posted by Trev on Stack Overflow See other posts from Stack Overflow or by Trev
Published on 2010-03-18T04:29:17Z Indexed on 2010/03/18 4:31 UTC
Read the original article Hit count: 268

Filed under:
|
|

Hello all,

First to give you some background: I have some research code which performs a Monte Carlo simulation, essential what happens is I iterate through a collection of objects, compute a number of vectors from their surface then for each vector I iterate through the collection of objects again to see if the vector hits another object (similar to ray tracing). The pseudo code would look something like this

for each object {
    for a number of vectors {
        do some computations
        for each object {
            check if vector intersects
        }
    }
}

As the number of objects can be quite large and the amount of rays is even larger I thought it would be wise to optimise how I iterate through the collection of objects. I created some test code which tests arrays, lists and vectors and for my first test cases found that vectors iterators were around twice as fast as arrays however when I implemented a vector in my code in was somewhat slower than the array I was using before.

So I went back to the test code and increased the complexity of the object function each loop was calling (a dummy function equivalent to 'check if vector intersects') and I found that when the complexity of the function increases the execution time gap between arrays and vectors reduces until eventually the array was quicker.

Does anyone know why this occurs? It seems strange that execution time inside the loop should effect the outer loop run time.

© Stack Overflow or respective owner

Related posts about c++

Related posts about optimisation