为什么类数组比结构数组消耗的内存多20%? [英] Why does an array of classes consume ~20% more memory than array of structs?

查看:57
本文介绍了为什么类数组比结构数组消耗的内存多20%?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在制作2D平台游戏,并使用2D瓷砖阵列表示一个级别,这些瓷砖是具有位置,类型和各种标志的字段的类.当我将图块类中的 class 关键字更改为 struct 时,加载的映射消耗的内存减少了约20%.

I'm making a 2D platformer game and to represent a level I'm using 2D array of tiles which are classes with fields for position, type and various flags. When I change the class key word in the tile class to struct, a loaded map consumes about 20% less memory.

我不知道此操作的是非,我只是想知道为什么内存消耗的差异.

I don't know about rights and wrongs of this action, I just want to know why the difference in memory consumption.

数字为1038 MB,以图块为类,结构为845 MB(没有大部分游戏数据).​​

numbers are 1038 MB with tiles as classes and 845 MB as structs (without most of game data).

推荐答案

对象数组实际上是引用数组,并且对象存储在堆中.

An array of objects is actually an array of references, and the objects are stored on the heap.

这意味着引用的开销为4或8个字节(取决于x86或x64),然后堆上的每个对象的开销为8或16个字节.

That means that there is an overhead of 4 or 8 bytes (depending on x86 or x64) for the reference, and then there is an overhead of 8 or 16 bytes for each object on the heap.

在结构数组中,结构值直接存储在数组中,因此没有额外的开销.

In an array of structs, the struct values are stored directly in the array, so there is no extra overhead.

因此,如果您的数据为48个字节,则额外的12个字节(在x86模式下)将占总内存使用量的20%.

So, if your data is for example 48 bytes, the extra 12 bytes (in x86 mode) would be an overhead of 20% of the total memory used.

请注意,它们的用法也有所不同.如果四处移动磁贴或将磁贴作为方法的一个参数发送,则使用结构时将复制所有数据,但如果使用类,则仅复制引用.如果您可以将结构保留为小于16个字节,则性能差异会很小,但是如果该结构较大,则可以通过使用类来获得更快的代码.

Note that there is also a difference in how they are used. If you move tiles around or send one as a parameter to a method, all the data will be copied if you use a struct, but only the reference is copied if you use a class. If you can keep the struct smaller than 16 bytes, the performance difference is small, but if it's larger you may get faster code by using classes.

这篇关于为什么类数组比结构数组消耗的内存多20%?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆