当前位置:网站首页>If you need a million objects
If you need a million objects
2020-11-09 23:53:00 【The way of architect's practice】
Design background
Every platform will have the basic data design of users , As the most basic user , Every user has many properties , Like gender , full name , Phone number etc. , Each user can also have an honor system like experience value , According to different experience value to correspond to different grade , Different grades correspond to different honors UI, For example, a primary user may only display one star , Second level users show two stars , And so on , Be similar to QQ Grade stars moon sun , Such an honor system is growing with the platform , There may be many types of derivatives . So here comes the question , Users need to initialize these honor values when logging in , Take the number of stars , Similar to the following code
public class Star
{
// Grade
public int Level{get ;set ;}
// The corresponding number of stars
public int StarNumber{get ;set ;}
// The corresponding star color
public int Color{get ;set ;}
... Other attributes
}
// User information
public class User{
public Star StarInfo{get ;set ;}
//... Other attributes of the user
}
// Initialize user information
User u=new User(){ StarInfo=new Star(){ Level=1, StarNumber=1,Color=1}};
Every login user will initialize a Star Property to represent the current user's Star Information , When there is 100 When ten thousand or more users are online at the same time , The same amount is instantiated in memory Star object , And other similar property objects . Can't so many duplicate objects be optimized ? Of course not. !!
Problem analysis
There's a business problem , First of all, we should analyze the problem . According to the above , The root of the problem is that there are a lot of objects , First of all, each user object has its own unique state , It's basically impossible to decompose optimization , But it's similar Star There is a way to optimize such attributes , One of the biggest commonalities of these honor attributes is immutability , let me put it another way , Grade 1 Of users Star Information will never change , Forever level=1,starnumber=1,color=1 etc. . Based on this invariance , We can take this Star Pulled out , For all levels 1 Used by , Suppose that there was 10 Ten thousand 1 Users of , The original need 10 Ten thousand objects , Now you only need one object , It's a big difference .
solve the problem
Based on the above analysis , What we need to do is reuse the object , As long as the object repeats the question , Basically, an object exit can be used to solve the problem , Similar to the following object initialization factory , But pay attention to thread safety , Because there will be multiple threads requesting and initializing objects at the same time .
public class UserStarFac
{
static object objLock = new object();
static Dictionary<int, Star> UserStarMap = new Dictionary<int, Star>();
public static Star GetUserStar(int level)
{
// Use locks to prevent multiple instantiations , Of course, it can be optimized here
lock (objLock)
{
Star info = null; ;
if(!UserStarMap.TryGetValue(level, out info))
{
info = new Star() { Color = 1, Level = 1, StarNumber = 1 };
UserStarMap.Add(level,info);
}
return info;
}
}
}
Write a simple test program
static void Main(string[] args)
{
int i = 0;
List<User> userList = new List<User>();
while (i < 100000)
{
// userList.Add(new User() { StarInfo=new Star() { Color=1, Level=1, StarNumber=1} });
userList.Add(new User() { StarInfo= UserStarFac .GetUserStar(1)});
i++;
}
Console.WriteLine(" Initialization complete ");
Console.Read();
}
Memory test results :
Do not perform any procedures : Take up memory :2.8 M
No optimization initialization 10 Ten thousand objects : Take up memory :11 M
Initialization after optimization 10 Ten thousand objects : Take up memory :7 M
Actually a small optimization is reduced 4M Memory , Don't look down on this little 4M, What you want to see is proportion , It's almost reduced 50%, In real business , There are countless places where this optimization can be done , I don't know if you care ?
This problem of a large number of duplicate objects, especially in game programming, often exists , For example, Gobang game , Initialization of chess pieces , There are millions of matches in a game hall , If the pieces in each game initialize an object , That memory usage is pretty scary , This kind of need puts the general object property , Invariant object attributes are extracted , It's necessary to share .
It is said that there is a scientific name for this optimization : The flyweight pattern , There is no need to remember the name , But you need to remember the principles and the scenarios , It must be mentioned that : Pay attention to the constant object
More wonderful articles
版权声明
本文为[The way of architect's practice]所创,转载请带上原文链接,感谢
边栏推荐
- Guest interview: Wang Jian
- What is the architecture of a live broadcast system worth more than $1 billion?
- Fear of reconstruction? I'm too late to tell you how to refactor. Now I'm here
- Coding style: SSM environment in MVC mode, code hierarchical management
- jt-京淘项目
- 接缝雕刻算法:一种看似不可能的图像大小调整方法
- Top 5 Chinese cloud manufacturers in 2018: Alibaba cloud, Tencent cloud, AWS, telecom, Unicom
- 2020-11-09:谈谈布隆过滤器和布谷鸟过滤器的相同点和不同点?
- 公网IP地址和SSL证书可以提升SEO吗?
- z-index属性详解
猜你喜欢
JMeter的简单使用
Explanation of Z-index attribute
Apache Hadoop的重要组成
Exhibition cloud technology interpretation | in the face of emergencies, how does app do a good job in crash analysis and performance monitoring?
Functional guide for temporary users and novices of PL / SQL developer
js解决浏览器打印自动分页的问题
Hand in hand to teach you to use container service tke cluster audit troubleshooting
Promote China manufacturing upgrade, 3D visualization of production line in automobile assembly workshop
一幅图像能顶16x16字!——用于大规模图像缩放识别的变压器(对ICLR 2021年论文的简要回顾)
Win7 + vs2015 + cuda10.2 configuration tensorrt7.0
随机推荐
Simple use of JMeter
【LeetCode】 92 整数反转
Apache Hadoop的重要组成
Important components of Apache Hadoop
接缝雕刻算法:一种看似不可能的图像大小调整方法
asp.net core中使用Serilog以及自定义Enricher
Python提示AttributeError 或者DeprecationWarning: This module was deprecated解决方法
CUDA_主机内存
恒讯科技浅谈:出现服务器宕机的处理方式
Usage of [:] and [::] in Python
Can't find other people's problem to solve
Application of V7 version of lvgl Library
Operation and design of rights management in ERP
How SSL certificate and public IP address affect SEO
CUDA_常量内存
Brief analysis of LinkedList source code
mongodb内核源码实现、性能调优、最佳运维实践系列-command命令处理模块源码实现一
Software engineering in code -- source code analysis of menu project
11.9
[leetcode] 92 integer inversion