Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the correct way to clear an array in Haxe?

Tags:

haxe

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.

like image 926
montonero Avatar asked Jul 26 '17 10:07

montonero


1 Answers

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:

  • Splice: 0.51 seconds
  • Length: 0.069 seconds
  • Assignment: 0.34 seconds
  • Pop: 0.071 to 0.179 seconds (scales linearly as the array gets bigger)

In HTML5:

  • Splice: 0.29 seconds
  • Length: 0.046 seconds
  • Assignment: 0.032 seconds
  • Pop: 0.012 seconds

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.

like image 146
Auroratide Avatar answered Nov 24 '22 19:11

Auroratide