Can we optimize C++ operator overloads ?
Dear C++ experts, can we optimize the C++ operator overloads by preventing creation of temporary variables?
Generally C++ operator overloads are frowned upon due to performance degradation caused by dynamic memory allocation used while creating and deleting temporary objects in operations such as veca + vecb - vecx * vecy. Code:
VECTOR operator+(VECTOR& a, VECTOR& b) Now, what if we were able to use pre-allocated objects instead of creating new ones? Code:
VECTOR operator+(VECTOR& a, VECTOR& b) |
You can define an add function
Code:
class VECTOR I think Chapel can do in place updates. See slide 13 here https://chapel-lang.org/CHIUW/2020/C...-Chapel101.pdf which shows a similar operation as in your question. I wrote some simple example codes in Chapel here https://github.com/cpraveen/cfdlab/tree/master/chapel |
Quote:
I'm planning to use a free mathematical functions like you showed for some operations, if the C++ operator overload can't be optimized, and I don't have enough RAM to store the intermediary vectors or matrices in the method I mentioned. some operation like `res = a+b+c+d+e+f+g+h` could be simplified into add(res, a,b,c,d,e,f,g,h), without needing to write loops, but I have to see what new features of C++ I can use to do it and make the function take arbitrary number of arguments. Probably through variadic templates, it will be possible. Of course, the final aim would be to be able to write very complex operations like `res = a.dot.b + b.cross.c + div(delta)` etc in a compact form, but I don't know if it's possible.:confused: |
Quote:
I have a reaaaaaalllyyy bad idea on how we can get "similar" compact mathematical form of Fortran, in C++. :rolleyes: Code:
|
Have you looked at "Expression Templates", see
https://en.wikipedia.org/wiki/Expression_templates It describes almost same situation which you are asking. |
Quote:
I created an Expression Template library last year. Not worth the effort. Highly overrated in my humble opinion, as it becomes very difficult to find optimization possibilities in the code. I came up with a hack to make it a little bit easier to work with such long expressions. I just want to write simple code for N dimensional arrays, like in Fortran 95, but in C++. Looks like the operator overloading may not be the best solution. This hack works for now, I guess. Code:
#include <iostream> Code:
1 + 2 = 3 |
My macro based "hack" might actually be a very good solution.
It feels good to write, it feels fast to write, it feels easy to read, and it doesn't break anything as far as I know. Using it in my codebase from now on. |
All times are GMT -4. The time now is 11:30. |