减少类成员变量中不必要的相同值
class A
{
public int a;
public int c;
}
我将从 A 创建 10 个实例。然后我将再次从 A 创建 15 个实例...继续。前 10 个实例将具有相同的变量值,接下来的 15 个实例将再次具有相同的 a 值。但我并不是说两个组都具有相同的 a 值。问题是在第一组和 15 中创建相同的 a 值 10 次第二组的时间对记忆来说是不必要的。
在这种情况下减少不必要数据的最佳解决方案是什么?
class A
{
public int a;
public int c;
}
I will create 10 instances from A.Then I will create 15 instances from A again... go on. first 10 instance will have same value for a variable and next 15 instances will have again same value for a.But I don't mean that both group has same values for a .Problem is create same a value 10 times in first group and 15 times in second group on memory unnecessary.
What would be Best solution or solutions for reduce unnecessary datas in this situation?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果
a
和c
实际上只是整数,那么就不值得花时间尝试从内存空间中优化它们;在大多数情况下,您用来执行此操作的任何内容都会比整数本身占用更多的空间。但是,如果
a
和c
实际上是占用大量内存的对象,您可以将对象指针(或持有者,取决于语言)作为A
而不是对象本身。这样唯一的内存在指针中重复。If
a
andc
are actually just integers, it won't be worth your time trying to optimize them out of the memory space; in most cases, anything you would use to do so would take up more space than the integers themselves.However, if
a
andc
are actually objects that take up a significant amount of memory, you could instead put object pointers (or holders, depending on the language) as members ofA
instead of the objects themselves. That way the only memory duplicated in the pointer.很明显,静态成员无法解决此问题。因为实例组将具有不同的值。
这可以是解决方案之一。还有什么其他解决方案?
It is clear that static member will not work for this problem.Because instance groups will have different values.
this can be one of the solutions.What can other else ?
另一个解决方案是
而不是创建新的 int 实例?类我们应该分配相同的实例。但是强制转换int?转换为 int 会很难使用并导致性能问题。
Another solution is
but instead of create new instance of int? class we should to assign same instance.But casting int? to int will be ugly to use and cause performance issues.
HashSet
有帮助吗?Would a
HashSet<T>
help?