x


How do I Resize an Array in JS?

So, Newbie me just got introduced to .NET array methods by our shepherd Eric5h5. Tried System.Array.Copy, nearly made me cry with a mixture of joy at the prospect of not having to write a new function for each new class I'm resizing an array of, and frustration with having already typed so much useless code... I then tried System.Array.Resize(myArray, myArray.length+1); nope. Is my syntax wrong, or is there only a limited set of .NET methods which we can use in Unity's javascript? If so, where's the list? And are there any iOS compatibility issues? If yes, it would at least make my array manipulation skills less obsolete...

Thanks in advance!

more ▼

asked Dec 13, 2011 at 11:20 PM

gregzo gravatar image

gregzo
3.2k 120 90 109

I fully agree with @syclamoth that Lists are superior to arrays for dynamic size scenarios. I understand that you might want to fully grasp the methods coupled with arrays, but the brutal practical fact is that you'll be using these functions extremely rarely. I've worked professionally for 3-4 years and I've been programming C# for several years more and I've never had to use it, not even once. You'll be doing yourself a great favor if you move on to List, which is a typical class you'll be working with a lot.

Dec 13, 2011 at 11:32 PM Statement

Why not use lists? They have functionality that arrays do not. Arrays aren't really meant to be resized or anything- they're the simplest data structure.

Dec 13, 2011 at 11:24 PM syclamoth
(comments are locked)
10|3000 characters needed characters left

1 answer: sort voted first

System.Array.Resize is a template method and the only way I can get it to work with JS is to explicitly define the template parameter. So yes, your syntax was a bit off there, but here's how it should look:

 var myArray : int[];
 System.Array.Resize.<int>(myArray, myArray.length + 1);
 print(myArray.length);

Given myArray is initially 5, running this script will print "6". I hope this little snippet is self explainable but if you have questions, just post a comment to this answer and I or someone else will get back to you.

The code you posted would generate this error message:

Assets/MyArray.js(2,20): BCE0023:

No appropriate version of 'System.Array.Resize' for the argument list '(int[], int)' was found.

The method clearly is there, it's just hidden as a template method (meaning you can replace the type of the array). The syntax for specifying the template parameter is added as .<T> to the method name, where T is the type of elements in the array.

more ▼

answered Dec 13, 2011 at 11:37 PM

Statement gravatar image

Statement
26.2k 76 114 254

Thanks , I was expecting it had something to do with type, seeing that T, but didn't know the proper syntax... Are lists as fast as arrays? I need the code to be super efficient, as I'm resizing big 2d arrays quite often in a musical game based on user friendly, custom built sequencers, and sync needs to be perfect. What about iOS compatibility? No worries there? Will take a look at List anyway.

Dec 13, 2011 at 11:51 PM gregzo

Don't worry too much. Worry only when you start noticing hiccups or slowdowns. Just go ahead and use List as your best friend until you notice you need to optimize. And chances are you'll still be using lists even after the optimization because it's likely that you'll want to use them in your optimized solution, which may differ greatly from your old solution. Also, for 2d data, arrays are probably to be preferred since lists are a pain in the butt when it comes to 2d data. But instead of resizing the arrays over and over again, maybe you can come up with a class that chain multiple 2d chunks together so it appears to the client code as a continuum/endless 2d field.

Dec 14, 2011 at 12:18 AM Statement

If you are resizing arrays frequently (as you say you do), it means you're reallocating memory frequently. This will put stress on the garbage collector and cause slowdowns and hiccups. It will fragment your memory and the memory manager will start to defragment your memory (given it works somewhat similar to usual .NET memory manager) causing large memory moves that may temporarily stall your program. I don't have the knowledge of your implementation details, but maybe you can find a solution that doesn't throw away your big chunk of memory each time you have to resize? Store only the data you need to, if you have a scenario where a lot of the elements are empty. Use lists if you use 1d data. Use chunks of 2d arrays if you use 2d data but encapsulate that memory management logic in a easy to use class.

I used Reflector to look at Array.Resize, where you can see that the old array is discarded and a new array is created. That's a new memory allocation right there, and they are expensive.

 [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)]
 public static void Resize<T>(ref T[] array, int newSize)
 {
     if (newSize < 0)
     {
         throw new ArgumentOutOfRangeException("newSize", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
     }
     T[] sourceArray = array;
     if (sourceArray == null)
     {
         array = new T[newSize];
     }
     else if (sourceArray.Length != newSize)
     {
         T[] destinationArray = new T[newSize];
         Copy(sourceArray, 0, destinationArray, 0, (sourceArray.Length > newSize) ? newSize : sourceArray.Length);
         array = destinationArray;
     }
 }
Dec 14, 2011 at 12:37 AM Statement

Well, in the end it's all ones and zeros anyway- there's no point worrying about the way they work internally since at some point it all becomes kind of ridiculous. The fact is, the .net framework provides us with tools, and you'd be crazy to make your own instead of using the one that are there for you.

Dec 14, 2011 at 01:00 AM syclamoth

@syclamoth, about ones and zeroes. Trivial types such as int and float doesn't require the memory manager to keep track of the references as it would (presumably) do if you are using reference types, such as the class GameObject, so there's a bit more than ones and zeroes there. :) And yes, it can get ridiculous pretty quickly if you start digging too deep. I almost lost myself there a moment, but then again I really love these .NET discussions. Naturally you should avoid reinventing the wheel and performance issues lie often elsewhere than a simple List or Dictionary.

Dec 14, 2011 at 01:06 AM Statement
(comments are locked)
10|3000 characters needed characters left
Your answer
toggle preview:

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Topics:

x6290
x2248
x154
x138
x118

asked: Dec 13, 2011 at 11:20 PM

Seen: 4541 times

Last Updated: Dec 14, 2011 at 07:16 AM