我读过很多关于页面如何因过度使用 Viewstate 而陷入困境的文章,我不确定是否使用逗号分隔的字符串(可能为 3 - 4 个单词)并将其拆分为数组
string s = 'john,23,usa';
string[] values = s.Split(',');
检索将有所帮助,因为我看到我的许多同事正在这样做,大概是为了提高页面加载性能。任何人都可以建议吗?
请您参考如下方法:
实际上,它在某些情况下确实有所作为,但它看起来很棘手,而且往往无关紧要。
见以下案例:
示例显示了 ViewState 的大小(以字节为单位),这意味着没有任何内容的页面会产生 68 字节的 ViewState。 其他所有内容都是手动加载到 ViewState 的内容。
将字符串值 0..9999 放在 ViewState 上。
string x = string.Empty;
for (int i = 0; i < 10000; i++)
{
if (i != 0) x += ",";
x += i;
}
//x = "0,1,2,3,4,5,6,7,8...9999"
ViewState["x"] = x;
//Result = 65268 bytes
还有一个数组:
string[] x = new string[10000];
for (int i = 0; i < 10000; i++)
{
x[i] = i.ToString();
}
ViewState["x"] = x;
//Result = also 65268 bytes
当在可覆盖的 SaveViewState 方法上返回时,上述两种情况都会产生 65260 字节的 ViewState。比将其加载到 ViewState 对象上少 8 个字节。
但是,在其他一些情况下:
//104 bytes
ViewState["x"] = "1,2,3,4,5,6,7,8,9,10"
// 108 bytes
ViewState["x"] = new string[] { "1", "2", "3" , "4", "5", "6", "7", "8", "9", "10"}
如果重写页面的SaveViewState 方法:
protected override object SaveViewState()
{
//100 bytes
return new string[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10" };
//100 bytes
return "1,2,3,4,5,6,7,8,9,10";
}
由于 ViewState 是加密的并且是 Base64 编码的, 在某些情况下,它可能只是对两个不同的对象进行字符串编码,从而为页面生成两个不同的输出。
