Why is this D code slower than C++?
Bradley Smith
digitalmars-com at baysmith.com
Thu Jan 18 10:13:52 PST 2007
Bill Baxter wrote:
> %u wrote:
>> Bill Baxter Wrote:
>>> D still not as fast as the C++, but close.
>>
>> I refuse to analyze this any further.
>>
>> On comparing the implementations of Primary, I noticed, that the OP
>> has introduced a constructor which executes "new Material". There is
>> no "new" in the cpp-version of Primary but a "SetMaterial" function.
>>
>> On deleting the new expression in the D-version an exception was
>> raised on executing the newly compiled binary.
>>
>> Astonishingly grepping over the .cpp and .h -files with agent ransack
>> no calls of "SetMaterial" were delivered---but "GetMaterial" is
>> called---which uses the unset "Material" pointer. :-(
>>
>> Conclusion: at least one of the following is true
>> 1) I have near to no ability to understand c++ 2) the c++-version is
>> lucky to run at all
>>
>> In case of 2) the OP has silently changed the algorithm on porting to D.
>
> It's case 1) I'm afraid. :-)
>
> Material is a by-value member of Primitive in the C++ version. This
> means it acts more like a D struct than a D class. GetMaterial calls
> return a pointer to the Material that's part of the class, and it will
> have been initialized implicitly by the Primitive constructor using
> whatever Material's default constructor does.
>
> So the C++ code is ok. But it's not clear why Material became a class
> in the D version rather than a struct.
Because in the C++, GetMaterial returns a pointer. Since other objects
can use the pointer to change the value of the Material contained within
a Primitive, the same behavior was used in the D code by using a class.
If a struct had been used, a copy of Material would be returned, and
changing the Material would have no effect on the Primitive.
Also, because GetMaterial is called very often, I assume that making
lots of copies of it would decrease performance. Presumably, that is why
the C++ code returns a pointer.
Thanks,
Bradley
More information about the Digitalmars-d-learn
mailing list