#In terms of speed ... does Complex(f64).init(...) incur run-time cost??

1 messages · Page 1 of 1 (latest)

steel surge
#

Doing complex number computations in an inner loop, speed in the important thing here! Should Complex(f64).init be avoided or not?? Two examples, which would be faster??:

inline fn sub(a: anytype, b: @TypeOf(a)) @TypeOf(a) {
    return @TypeOf(a).init(a.re - b.re, a.im - b.im);
}

or

inline fn sub(a: anytype, b: @TypeOf(a)) @TypeOf(a) {
    var c: @TypeOf(a) = undefined;
    c.re = a.re - b.re;
    c.im = a.im - b.im;
return c;
}

Would there be other alternatives that would be faster?

(Yes, there is the complex math function for subtraction, but this is just example. The question is about how to "create" the returned variable.)
I believe they would be exactly the same, but am unsure, I could not get this working on godbolt. Thanks in advance.

toxic zodiac
#

The init function should get inlined by any remotely sane backend, so will have no runtime cost other than two copies

#

tbh even if it for some reason didn't get inlined it wouldn't have any major cost since it's just an unconditional call

steel surge
#

I ask because in the inner most loop, just a small overhead of function calls can become painful, when the actual computations of the function are so small (such as with the subtraction above).

The interest is to as efficiently as possible come around the lack of overloading and macros... because writing out the individual steps of complex arithmetic is tedious and error-prone.

toxic zodiac
#

Yeah that's fair, I'd be happy saying with confidence that small init functions like that will be inlined