gpt4 book ai didi

java - 指针 - 减少内存消耗

转载 作者:行者123 更新时间:2023-11-30 11:31:26 26 4
gpt4 key购买 nike

我一直在为 OpenGL 练习编写一个 Minecraft 副本(我猜有很多),但是在编写基本渲染 API 之后,我注意到真正的 Minecraft 使用了 很多 或内存 - 大约 800MB!我可以完全理解为什么这是它必须记住的所有方 block 以及生成器的生物和可能的地形数据......我问自己“这个方 block 与那个方 block 完全一样......它们可以在代码中吗? “并且记得 C++ 有指针,所以我试图在 Java 中做同样的事情,这是我能想到的唯一方法,为每个 block 创建一个静态实例而不使用 new 关键字,这是最好的方法吗?它似乎确实有帮助..如果可能的话,我仍然希望它变得更好?
这是有问题的类(class)..

public abstract class Block {
public static DirtBlock Dirt = new DirtBlock();
public static GrassBlock Grass = new GrassBlock();
public static RedstoneOreBlock RedstoneOre = new RedstoneOreBlock();
public static TNTBlock TNT = new TNTBlock();
public static MonsterSpawnerBlock Monserspawner = new MonsterSpawnerBlock();
public static BedrockBlock Bedrock = new BedrockBlock();
public static StoneBlock Stone = new StoneBlock();
public static GlassBlock Glass = new GlassBlock();
public static SandBlock Sand = new SandBlock();
public static WaterBlock Water = new WaterBlock();
public static SnowBlock Snow = new SnowBlock();
public static SnowGrassBlock SnowyGrass = new SnowGrassBlock();
public static IceBlock Ice = new IceBlock();
public static CoalBlock Coal = new CoalBlock();

对于一个 100 block 世界,当前内存使用量约为 200MB,每个 block 由 16 block 宽 x 64 高和 16 深组成,总共 1,638,400 个 block - 每个 block 约 128 字节。

最佳答案

,这是个好办法。它被称为 Flyweight 模式。但是考虑使用对象工厂而不是静态字段。从长远来看,这将使您的代码更易于测试。

In computer programming, flyweight is a software design pattern. A flyweight is an object that minimizes memory use by sharing as much data as possible with other similar objects; it is a way to use objects in large numbers when a simple repeated representation would use an unacceptable amount of memory. Often some parts of the object state can be shared, and it is common practice to hold them in external data structures and pass them to the flyweight objects temporarily when they are used.

A classic example usage of the flyweight pattern is the data structures for graphical representation of characters in a word processor. It might be desirable to have, for each character in a document, a glyph object containing its font outline, font metrics, and other formatting data, but this would amount to hundreds or thousands of bytes for each character. Instead, for every character there might be a reference to a flyweight glyph object shared by every instance of the same character in the document; only the position of each character (in the document and/or the page) would need to be stored internally.

来自维基百科,http://en.wikipedia.org/wiki/Flyweight_pattern

关于java - 指针 - 减少内存消耗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17155662/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com