如果我有一个对象需要存储在viewstate中,我可以做些什么来优化存储对象所需的大小?显然,存储最少量的数据将占用更少的空间,但除此之外,是否有方法来构建类,属性,属性等,这将影响序列化输出的大小?
答案 0 :(得分:3)
我的基本观点。
另外我知道如果我在基类中使用额外的List,它们会占用更多空间。这是一个你自己可以通过玩我提到的点来看到的样本。
例如,如果从cEnaText中删除默认值,则viewstate比使用它小50%。如果将[NonSerialized]放在所有变量上,则视图状态为空。如果你的名字越大,那么viewstate就越大。
[Serializable]
public class MyInts
{
// this text will stored even if you never used it, Avoid to setup it here.
public string cEnaText = "Start up text";
// a work around for big names, and default text.
[XmlAttribute("TX")]
string inside_cEnaTextWorkAroundSolution;
// this is not going to saved on xml.
public string cEnaTextWorkAroundSolution;
{
get
{
// here I return a default text that I do not store on xml
if(string.IsNullOrWhiteSpace(inside_cEnaTextWorkAroundSolution))
return "This is my default string that I do not won to save";
else
return inside_cEnaTextWorkAroundSolution;
}
set {inside_cEnaTextWorkAroundSolution = value;}
}
// this is stored, including the class name
public int MyInt;
// this is not stored
public MyInts(int getInt)
{
MyInt = getInt;
}
}
[Serializable]
public class StoreMeAsTest
{
// this is stored
public List<MyInts> MyL = new List<MyInts>();
// keep the name small (not like this one)
public double cOneMoreVariable;
// or change the xml attribute name with this command
[XmlAttribute("ME")]
public double cOneMoreVariableEvenBigger;
// this is not stored
[XmlIgnoreAttribute]
public List<MyInts> Temporary = new List<MyInts>();
// this is not stored
public StoreMeAsTest()
{
// create some test data
for (int i = 0; i < 100; i++)
{
MyL.Add(new MyInts(i));
Temporary.Add(new MyInts(i));
}
}
}
public partial class Dokimes_Programming_Performance_ViewStatePerformance : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
StoreMeAsTest StoreMe = new StoreMeAsTest();
ViewState["MyTestTable"] = StoreMe;
}
}
有一些程序你可以阅读viewstate,这是我发现google的程序。
http://www.binaryfortress.com/aspnet-viewstate-helper/
我说您可以使用此功能来了解存储的内容和不存储的内容,以及要存储的信息量。通过这个技巧,您可以在文本中看到最终的序列化对象。
public static string ObjectToXML(Type type, object obby)
{
XmlSerializer ser = new XmlSerializer(type);
using (System.IO.MemoryStream stm = new System.IO.MemoryStream())
{
ser.Serialize(stm, obby);
stm.Position = 0;
using (System.IO.StreamReader stmReader = new System.IO.StreamReader(stm))
{
string xmlData = stmReader.ReadToEnd();
return xmlData;
}
}
}
这里我是如何使用这个功能的
MyLiteral.Text = ObjectToXML(typeof(StoreMeAsTest), StoreMe);
你实际问这里我们可以优化对象及其非常好的问题。下一步可能是压缩视图状态,使其在传输回我们时变小。
答案 1 :(得分:0)
答案 2 :(得分:0)
您可以将您的视图状态存储在服务器上 看看这个: