Search code examples
phparraysinitialization

Initializing a huge array (50000 entries)


I'm initializing a huge array of 49605 key=>value pairs) (the array will never be changed again) $boardkey_to_values=Array(97031=>0,97531=>1,409531=>2,410031=>3,410131=>4,472031=>5,472531=>6,472631=>7,472651=>7,484531=>8,485031=>9,485151=>10,485131=>10,...)

Thing is this takes a lot of time for the compiler (40ms in averages)

I wondered if there could be a faster solution.

I'm using a big subset of the keys in my programm (15-35k). I was using MySQL before with where_in, but it was even slower (6s in average), I was given the advice to hardcode it, and indeed, it is much faster but I wanted to optimize it even more. See the original post String to Value compare Optimizing MySQL Query


Solution

  • 40 ms isnt terribly slow for such a large array. But if this is on the web and multiple people are calling the PHP page, that can slow the server down. You have several options:

    • Use multiple Ajax calls, to populate your array, after the page has rendered, i.e. sets of 10000 every few seconds (This way you can do other stuff on the page and let the array populate in its own time)

    • Use a database, as it will be faster to search/update instead of storing it in an Array.

    • Change the program logic to only work with a few values at a time, instead of 49K of them. (kind of like pagination, where only a subset of the data is shown per page)