数组或对象来存储数据-什么是更好的解决方案


array or objects to store data - what is better solution

我只是在想什么能给我更好的性能和内存使用。我正在为一款游戏编写地图。所有内容都存储在"map"类中,但一个map可能有数千个tile。现在我在想什么是更好的解决方案:

  • 将每个tile参数保存在x-y数组中(tile x = 10, y = 11数据存储在数组中,如map[10][11] = params),如果我想知道一些关于tile的信息,可以调用带有x-y参数的不同数组
  • 考虑一个瓷砖作为一个对象,它可以很容易地返回瓷砖的邻居和所有数据也存储在每个对象的某个地方作为一个数组。

因为我可能有数千个类似的tile,第一印象是它最适合面向对象编程,但我担心数千个对象tile可能会使用更多的内存,并且调用它的方法可能会更慢。你觉得怎么样?

Kalreg

这取决于你使用的php版本。如果你使用的版本是PHP5或以上(你应该作为最新的php版本将意味着更多的性能为您的游戏应用程序),那么使用数组和对象将为您的应用程序提供几乎相同的性能。因此,如果您正在使用/可以使用PHP 5或更高版本,那么您可以根据自己的方便使用数组或对象。

检查这个数组与Aron Novak的对象比较/测试:http://aggregation.novaak.net/?q=node/227。我在下面引用Aron Novaks的话:

I created a small script to find out which data structure has better performance. You can find the script what I used for the test at the attachments.
My test results are:
    data structure          PHP4        PHP5
    object                  61.6224     37.576
    array                   57.6644     37.866
    The results are in milliseconds(ms). It seems that in PHP5 the data structure is totally indifferent, in PHP4 there is approximately 7% performance gain if use arrays instead of objects.
    "This revolution, however, left PHP's object model mostly unchanged from version 3 – it was still very simple. Objects were still very much syntactic sugar for associative arrays, and didn't offer users too many features on top of that." (http://devzone.zend.com/node/view/id/1717)
    So the syntactic sugar is not a bad thing at all :) And it costs almost nothing. This is an explanation why all the parsers' output uses objects.

查看此http://we-love-php.blogspot.com/2012/06/php-memory-consumption-with-arrays.html关于PHP数组与对象的内存使用和性能的详细/伟大文章

如果你正在开发一款游戏,你肯定不能只使用arrayobjects,你很可能会同时使用这两种方法。

我认为你应该首先了解PHP数组(和值)到底有多大?(提示:大!)

将你的数组替换为SplFixedArray并将你的对象存储在SplObjectStorage中,你应该会在你的代码中得到改进。

如果你有一个tile的网格,它非常适合存储在数组中。

但是如果这些贴图有很多附加信息,它们就会变成对象。

我建议使用对象数组

相关文章: