今天走在路上忽然想起一個問題,以前沒有深入的注意到。c#
問題:若是在WebForm頁面週期中若是一個對象頻繁建立,請求結束後又進行銷燬確定會對系統產生必定的性能影響,咱們都知道,當咱們每次new一個對象時,其都在內存中指定的堆上分配一塊空間,那麼建立這個對象而後銷燬(Response.End()執行後)這個對象確定要消耗服務器的時間及空間(尤爲是並行請求數量很大的時候,撐破內存也不是不可能),由於每一個請求都會建這個對象。而後你們有沒有注意到,有些類多是這樣的,舉個例子:服務器
public class PeopleServer { public PeopleServer() { } public string ToStringPeople(People p) { return string.Format("Name:{0},Age:{1};", p.Name, p.Age); } } public class People { public string Name { get; set; } public int Age { get; set; } }
那麼當咱們每次須要打印People時,咱們估計都須要ide
new PeopleServer();
這時,服務器端的內存中指定堆內就分配了一塊內存用於存儲新建立的PeopleServer對象,當執行結束時在銷燬這個對象,想想若是咱們的服務器會說話,那他確定會這樣罵你:尼瑪每次建立的對像都同樣,並且每次請求還都須要建立,你就不能只建立一個對象,你們的操做時都使用這同一個對象,那不就省事兒多了嗎?性能
嘿嘿 懂個人意思了嗎?接下來咱們這麼設計代碼:spa
public class PeopleServer { private static PeopleServer _people; public PeopleServer() { } public string ToStringPeople(People p) { return string.Format("Name:{0},Age:{1};", p.Name, p.Age); } //該方法必須爲靜態的方便其餘對象去調用 public static PeopleServer GetPeopleServer() { if (_people == null) { _people = new PeopleServer(); } return _people; } } public class People { public string Name { get; set; } public int Age { get; set; } }
看到GetPeopleServer這個方法是否是有種恍然大悟的感受?那麼咱們每次去格式化People這個對象是隻須要這麼幾行代碼:設計
People p = new People() { Age = 23, Name = "tongling" }; PeopleServer pServer = PeopleServer.GetPeopleServer(); pServer.ToStringPeople(p);
減小了內存堆得額外開銷系統固然會更快些,這就是幾天咱們要說的單例模式的應用場景,再好比某些配置數據,也就是對象信息在第一次建立後就不須要改變的只須要Get該對象信息的一些類的定義也能夠這麼來弄,懂得原理就可以在往後的項目中隨機應變了。orm
再補充一種單例模式的寫法:對象
public static PeopleServer GetPeopleServerByCache() { object obj = System.Web.HttpRuntime.Cache["PeopleServerCache"]; if (obj == null) { obj = new PeopleServer(); System.Web.HttpRuntime.Cache["PeopleServerCache"] = obj; } return (PeopleServer)obj; }
其實原理都同樣。內存
屌絲的生活就是這樣,打烊,睡覺
get