Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Multidimensional vs. jagged arrays

Discussion in 'Scripting' started by Jessy, Aug 22, 2009.

  1. Jessy

    Jessy

    Joined:
    Jun 7, 2007
    Posts:
    7,325
    Is there a performance difference between multidimensional and jagged arrays?

    In my current case, all of the sub-arrays that go into my "parent" array are the same size. I'll use a jagged array if it makes the code execute faster, though.
     
  2. apple_motion

    apple_motion

    Joined:
    Jul 2, 2009
    Posts:
    169
    I did a speed test long time ago, that is about the read out time of different array classes on a single call in UnityScript.

    a[i,j] // (.NET) needs 382ns

    a // (.NET) needs 27ns

    a // (Javascript) needs 190ns

    (I forgot the detail, I can't remember the test code that is using float or vector4, but I think the results are still good as a reference :p)

    PS. for comparison, a routine like this only spend 543ns ! ....
    c = 1 + sin(v1)*sin(v) +cos(v1)*cos(v)*cos(u-u0);
    k = Sqrt( 2 / c);
    x = k *cos(v)*sin(u-u0);
    y = k *( cos(v1)*sin(v) - sin(v1)*cos(v)*cos(u-u0) );

    so that, read out anything from an array is a very slow process :p

    to answer your question, I guess that will no major different unless you change the array to native. I believe flattened native array should be the best in performance, (but less convenience)

    Antonio Hui
     
  3. andeeeee

    andeeeee

    Joined:
    Jul 19, 2005
    Posts:
    8,768
    It depends on what you are using them for.

    If you will need to update or test all the elements in the array at once and the elements are small-ish struct or value types (eg, float or Vector3) then you'll gain some speed-up from a 2D array, because it uses the CPU cache better. Otherwise, there will be little or no difference. Jagged arrays are usually better from a coding point of view. The rows can be different lengths, and each row can be processed individually by a function that expects a 1D array. Generally, I'd use a 2D array where the two dimensions represent some kind of significant spatial or mathematical property, but a jagged array for everything else.