HaxeFoundation / HaxeFoundation/haxe

[C++] Compiler may generate temp allocations within a loop

Open
#6,924 7 comments 0 reactions 0 assignees View on GitHub
platform-cpp waiting-for-feedback
Dominant language
Haxe
Stars
6.9k
Forks
715
Avg merge
2d 2h
Merged PRs (30d)
11

Description

Certain use-cases may cause the compiler to generate temporary variables within a loop. On C++, especially, this causes a lot of garbage. This is affecting inside of very large loops where we process a lot of data.

Here's some example code that reproduces it:

```haxe
class Main {

public static function main () {

var test = new TestClass ();

var total = 0.0;

for (i in 0...10000) {

total += add (test.getRandom (), test.getRandom ());

}

trace (total);

}

private static function add (a:Float, b:Float):Float {

return a + b;

}

}

class TestClass {

public function new () {}

public function getRandom ():Float {

return Math.random ();

}

}
```

The relevant C++ generated code looks like:

```cpp
HXLINE( 5) ::TestClass test = ::TestClass_obj::__alloc( HX_CTX );
HXLINE( 7) Float total = ((Float)0.0);
HXLINE( 9) {
HXLINE( 9) int _g = (int)0;
HXDLIN( 9) while((_g < (int)10000)){
HXLINE( 9) _g = (_g + (int)1);
HXDLIN( 9) int i = (_g - (int)1);
HXLINE( 11) Float total1 = test->getRandom();
HXDLIN( 11) total = (total + ::Main_obj::add(total1,test->getRandom()));
}
}
```

Easier said than done, but putting the `Float total1` declaration outside of the loop would result in less garbage. In our case, we see this occur dozens of times within a large loop, leading to collections of up to a million objects.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.