@stebulba said:
My question is :
I don't know how c++ process the method array.size(), but in this exemple, the method is in my understanding is called thousand times.
for (int i = 0; i < splits; i++) {
for (int j = 0; j < final_polygon.size(); j++) {
int j_n = (j + 1) % final_polygon.size();
All Godot look using that way.
I'm not a C++ expert by any means and I've only started working heavily with the C++ side of Godot again in the last few months, so that is something to keep in mind. You probably want to ask on the devel
channel on the IRC, as that's where most of the core Godot developers can be reached.
The code shouldn't be running a thousand times, unless the number of splits (splits
) multiplied by the number of elements in the polygon (final_polygon.size
) equals a thousand or more. The code you have shown is nested for loop, where for each split in splits
, you go through every polygon in final_polygon
and then assign a variable to j_n
(which I assume is used later in the code).
That should not be better to do :
int array_count = final_polygon.size();
for (int i = 0; i < splits; i++) {
for (int j = 0; j < array_count; j++) {
int j_n = (j + 1) % array_count;
When they brush or making the polygon, the process is already onerous. Why we call the method size() for no reason if the size don't change. Should be a bit faster with a single int variable.
Source https://github.com/godotengine/godot/blob/master/modules/csg/csg_shape.cpp#L2086
Can you confirm I am wrong ?
Yes, it may be a little faster, as you are not assigning a new temporary variable each time you are in the inner nested loop. However, on the other hand, you are creating a new variable that exists outside of the two for loops and therefore will persist in memory for the duration of the function, which has a small memory footprint/cost.
That said, the performance loss/gain is probably minimal in most cases, unless you are looping over thousands of times. Not to say that it wouldn't be faster, because it would since you are caching the result, but how much faster, I have no idea and really depends on the speed of the size
function. You'd probably want to profile the code to know for sure, but I would expect it to be slightly faster. If you are sure that the final_polygon
variable will not change size during the entire operation, then I don't see any harm in moving the calculation outside of the for loop to save a little performance, if you want to go down that route.
Another thing that might be part of why the nested loops are written that way is code style, for better or for worse. Again, you should probably ask on the IRC and double check with the developers there to know for sure.