What would be the most performant way to clear an array in Haxe? Currently I am just assigning an empty array to the variable.
I found this on the Internet:
public static function clear(arr:Array<Dynamic>) {
#if cpp
arr.splice(0, arr.length);
#else
untyped arr.length = 0;
#end
}
Is this the best way? I am concerned with two targets, JS and CPP.
For the most part you can simply use reassignment to an empty array to clear the array; this only becomes problematic if the reference to the array is important. In that case, what you have works well.
That's about it for the answer, but for curiosity's sake, I decided to try timing some of the ways to clear arrays. Unfortunately, I haven't used Haxe in a while and something in my computer's configurations must have changed, so I can only compile to Neko and HTML5 at the moment. Regardless, results were interesting.
For the test, I ran four different clear algorithms through arrays ranging from 8 to 1048576 integers in length. The algorithms were as follows:
Splice Clear:
array.splice(0, array.length);
Length Clear:
untyped array.length = 0;
Assignment Clear:
array = [];
Pop Clear:
while (array.length > 0)
array.pop();
All times shown below represent the total time taken to perform the same operation one million times.
In Neko:
In HTML5:
These tests were run on a 64-bit Windows 7 machine and Firefox.
I'm a bit surprised the while loop method was the fasted algorithm in javascript; it makes me think something is going on there. Otherwise, the length method is good on platforms that support it.
My tests are on Github in case anyone wants to peer review the methods and perhaps try out the tests on platforms other than Neko and HTML5.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With