Fastest alternatives to flattening a non-uniform nested array with regex?

Hello,

I'm looking at simplfying a function that flattens an array, it uses recursion and filters objects by type but this seems to be a waste of resources to me at least, using conditionals like this seems like a bad idea.

The array can be a generic type, int, string, float but not some container with mixed types.

For example

myArray:[Int]=[[-2, 5], 16, [-6, [9, [-3, [3, 1, 0]]]]]
for element in myArray 
{
  flatArray.append(element as! Int)
} else if element is [Any] { 
  recursionResult = flattenArray(nestedArray: element as! [Any])
  for num in recursionResult {
    flattenArray.append(num)
   }
}

The final result for this would be

[-2,5,16,-6,9,-3,3,1,0]

So I came up with this simple regex

/\-?[0-9]/g

Is there a more efficient way?
Thanks.

My opinion:

As a general solution that seems fine. I have not validated it. Are you encountering performance problems?
BTW the PCRE regex is very well optimized and is regex-directed, so you can switch to that on most linux boxes with no problems.

Not that the 'old' regex code is not optimized.

I like your solution, but I wonder about what you are seeing as a problem. Selecting a regex engine is a lot messier than in long ago times:
Comparison of regular expression engines - Wikipedia

However PCRE is considered to be as good as it gets. You could write a simple single purpose C program....

1 Like

Thanks for the comments.

Yes, I tried some long, really off-the-wall, random arrays that would be equivalent to a messy json structure and the simple regex easily beat the recursion.

Good idea about C code, what do you think about the performance gain and memory utilization of using a threaded version? versus openmp/mpi? or versus GPU, if the incoming array is a continuous stream from a web socket? or similar.

For single precision, Int16 or UInt16, it seems like GPU would crush this problem but I'm unsure of the overhead required for the memory allocation.