The general advice for optimizations is to do profiling first. I assume you already did it, and found that your "copy and access operations" (as described in the question) have to be optimized.
In this case, let me note that the name ExpensiveFunction
is misleading, because it cannot possibly be expensive when a few copy and access operations are so significant in your code.
The "general pattern" for optimizing is: look at your inner loop, and try to remove unnecessary operations.
In your case, you have the following there:
for (...; j < now->size(); ...)
- try replacingnow->size()
byM
- there is a good chance your compiler already did it, but you never know...if (j > 0 && < j < N)
- you can remove these checks completely if you separate your loop into 3 parts (first iteration; middle iterations; last iteration)now[j-1], now[j], now[j+1]
- some c++ implementations insist on array bound checking for each access (this is not required by c++); if yours is like this, try disabling the check, or replace yourstd::vector
bystd::array
or (if it doesn't help) by a C-style arraynext[i] = ...
- as above- You can try optimizing the code in your expensive functions instead...