Jer*_*emy 5 asp.net viewstate serialization binary-serialization
如果我有一个对象需要存储在viewstate中,我可以做些什么来优化存储对象所需的大小?显然,存储最少量的数据将占用更少的空间,但除此之外,是否有方法来构建类,属性,属性等,这将影响序列化输出的大小?
我的基本观点。
我还知道,如果我在基类中使用额外的列表,它们会占用更多空间。这是一个示例,您可以通过尝试我提到的要点来自行查看。
例如,如果您从 cEnaText 中删除默认值,则视图状态将比使用它时小 50%。如果将 [NonSerialized] 放在所有变量上,则视图状态为空。如果你把名字变大,那么视图状态就会变大。
[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;
}
}
Run Code Online (Sandbox Code Playgroud)
有一些程序可以读取 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是我如何使用这个功能
MyLiteral.Text = ObjectToXML(typeof(StoreMeAsTest), StoreMe);
Run Code Online (Sandbox Code Playgroud)
您实际上在这里询问我们可以优化该对象及其非常好的问题。下一步可能是压缩视图状态,使其在传输回我们时更小。
| 归档时间: |
|
| 查看次数: |
831 次 |
| 最近记录: |