Well, each hash has an overhead. This isn't that much but if you end up only putting 11 items in, then percentage-wise it isn't trivial. Also, with 11 items, each hash should end up with 16 buckets. With 121 items, my hash should have 128 buckets (versus 176). So it isn't a huge win.

You updated your node to use something like $grid{$x}{$y}{item}. Here the space savings of $grid{$x,$y,$item} could be even greater, though it also illustrates the main problem with this technique: You can no longer use $grid{$x}{$y}, for example, to pass to a subroutine that wants to just use $_[0]{item}, $_[0]{other}.

Without the preallocation, the hash would start out with 8 buckets, then grow to 16, then 32, then 64, then 128. Since this is one of those case where we know exactly how many items we plan to store, we can save time and some memory fragmentation by just jumping to 128 buckets at the start. This doesn't stop you from adding fewer or more items; the hash will still grow further if it needs to. This will only very rarely make much difference, however. I threw it in since I was specifically thinking about the memory impact of the data structure at the time.

The real point is that you probably have no use for $grid{$x}. That is, unless the game does a lot of manipulations to one row at a time. But then, if it also does work on one column at a time, then optimizing the row case may not be worth the effort.

Most of the time you are better off just ignoring this type of stuff. You can waste a lot of thought and time trying to preoptimize your data structures and code. (:

        - tye (but my friends call me "Tye")

In reply to (tye)Re2: 2D Arrays as a Gameboard by tye
in thread 2D Arrays as a Gameboard by gregor42

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.