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

1

7

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.

Wabble answered 26/7, 2017 at 10:21 Comment(0)
R
9

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.

Rikkiriksdag answered 27/7, 2017 at 3:10 Comment(1)
array = []; creates a new instance, which might lead to unexpected results if you have references to the old array.Botchy

© 2022 - 2024 — McMap. All rights reserved.