优化Settings类中的读写操作
本文关键字:读写 操作 Settings 优化 | 更新日期: 2023-09-27 18:25:19
使用Properties.Settings.Default
保存UI设置非常好。我可以使用直接从任何类获得它,但也可以使用对所有内容进行样式设置
FontSize="{Binding Source={x:Static p:Settings.Default}, Path=MyFontSize, Mode=OneWay}"
我担心用is做任何事情都会使我的程序变慢。
这段代码大约需要500毫秒:
bool b;
for (int i = 0; i < 100000; i++)
b = Properties.Settings.Default.testbool;
我不知道这是什么样的对象,但我希望有一种方法可以制作出具有类似属性但速度更快的东西,我可以在程序关闭时将其保存到设置中。
免责声明:我不建议执行以下操作。
如果真的想提高它的性能,你可以重定向Settings类的索引器从字典中读取:
internal sealed partial class Settings
{
private bool _isLoaded = false;
Dictionary<string, object> _tempValues = new Dictionary<string,object>();
public override object this[string propertyName]
{
get
{
if (_isLoaded)
{
return _tempValues[propertyName];
}
else
{
return base[propertyName];
}
}
set
{
if (_isLoaded)
{
_tempValues[propertyName] = value;
}
else
{
base[propertyName] = value;
}
}
}
protected override void OnSettingsLoaded(object sender, System.Configuration.SettingsLoadedEventArgs e)
{
base.OnSettingsLoaded(sender, e);
_isLoaded = true;
foreach (SettingsProperty property in Properties)
{
_tempValues[property.Name] = base[property.Name];
}
}
protected override void OnSettingsSaving(object sender, System.ComponentModel.CancelEventArgs e)
{
foreach (SettingsProperty property in Properties)
{
base[property.Name] = _tempValues[property.Name];
}
base.OnSettingsSaving(sender, e);
}
}
基准代码:
static void Main(string[] args)
{
Stopwatch timer = new Stopwatch();
timer.Start();
bool c;
for (int i = 0; i < 1000000; i++)
{
c = Properties.Settings.Default.MyBool;
}
timer.Stop();
Console.WriteLine(timer.ElapsedMilliseconds);
Console.ReadLine();
}
之前时间:1348ms
之后的时间:101ms