Re: Array optimizing problem in C++?
On Mar 23, 9:08 am, Razii <DONTwhatever...@hotmail.com> wrote:
From an old post by James Kanze
On Apr 9 2003, 5:42 pm, ka...@gabi-soft.de (James Kanze) wrote:
When I pass an "array" to a function in C/C++, I actually pass
a pointer to the first element. And the compiler, when it compiles the=
function, only sees pointers -- it has no way of determining any
relationship between them. Consider, for example, a smoothing function
(in C or earlier C++):
void
smooth( double* dest,
double const* src,
size_t len )
{
for ( size_t i = 1 ; i < len - 1 ; ++ i ) {
dest[ i - 1 ] = (src[ i - 1 ] + src[ i ] + src[=
i + 1 ]) / 3 ;
}
}
The compiler cannot arrange to use the src[ i + 1 ] value from the
preceding pass through the loop as the src[ i ] value in the current
pass, since the write to dest[ i - 1 ] might have changed it. In Java,=
it can, since two arrays are either identical or disjoint.
This sort of code shows up frequently. In benchmarks from Java
suppliers comparing Java to C++, of course:-). But also in any number
of applications dealing with physical measures: meteorology, geophysical
research (oil prospection), etc.
Out of curiosity, I tried to test if the above is true. It didn't make
any difference. In fact, C++ was a bit faster (not by much, just 6%).
Probably due to array bound check in Java, if there is in indeed an
issue with C++ arrays, overall there is no difference.
The issue C++ has with arrays is known as pointer aliasing. C has the
keyword "restrict" to deal with this problem but not C++. The
"restrict" keyword should be added in the next C++ standard. Most C++
compilers currently propose their own "restrict" keywords though.
Anyway, C++ has std::valarray. Arrays constructed with std::valarray
are free from aliasing. So, in the absolute, the Java language has no
performance edge over the current version of the C++ language in this
domain. However, even if theorically, std:valarray is free from
pointer aliasing, in practice, this isn't always the case, depending
on the compiler.
if there is in indeed an issue with C++ arrays, overall there is no differ=
ence.
With the right optimization flags, the smooth function would probably
get inlined, and static analysis of pointer aliasing should happen,
allowing the C++ compiler to perform no aliasing optimizations.
Probably due to array bound check in Java
A good java compiler should have applied bounds checking elimination
in this case especially since the smooth function should be inlined.
As a side note, your program should handle ints instead of doubles, to
focus more on the performance of array access.
Alexandre Courpron.