我能夠通過緩存它會在構造函數/初始化過程的數據庫實例,以在性能上的巨大差異執行1000次
感謝。現在我看到的是2-3倍的速度,取決於情況和運行。
1)如果只調用默認構造函數,並且具有所有相同的速度優點,那麼只需使用靜態實例替換_db即可正常工作。
// MyProject.MyDB _db;
// replace with a static instance, and remove the "this." from other lines
static MyProject.MyDB _db = new MyDB();
public MyClass() {
//_db=new MyProject.MyDB();
Init();
}
2)我已經寫了一個小緩存類數據庫條目和我打電話說在所有的老地方我ActiveRecord.tt文件,其中「新的()」中使用。
// REPLACE "MyDB" with the name of your DB. Alternately, include this
// class in Context.tt and have it generate the correct name.
class ContextDatabaseCache {
public static MyDB GetMyDB()
{
return GetInstance("~~default~~",() => new MyDB());
}
public static MyDB GetMyDB(string connectionString) {
return GetInstance(connectionString,() => new MyDB(connectionString));
}
public static MyDB GetMyDB(string connectionString, string providerName)
{
return GetInstance(connectionString + providerName,() => new MyDB(connectionString, providerName));
}
private static Dictionary<string, MyDB> _dict = new Dictionary<string, MyDB>();
private static MyDB GetInstance(string key, Func<MyDB> createInstance)
{
if (!_dict.ContainsKey(key)) {
lock (_dict) {
if (!_dict.ContainsKey(key)) {
_dict.Add(key, createInstance());
}
}
}
return _dict[key];
}
///<summary>Call this when the "DefaultConnection" string changes in the
/// App.exe.config file so that a new db instance will be created
/// and pick up the changed value. </summary>
public static void Clear() {
_dict.Clear();
}
}
這是已在ActiveRecord.tt文件進行替換的類型:
public <#=tbl.ClassName#>(){
_db=new <#=Namespace#>.<#=DatabaseName#>DB();
Init();
}
// becomes this:
public <#=tbl.ClassName#>(){
_db= <#=Namespace#>.ContextDatabaseCache.Get<#=DatabaseName#>DB();
Init();
}
您比較了爲ActiveRecord/SimpleRepository執行的SQL嗎? – 2010-01-17 15:46:17
您是否已經完成了Adam的建議。如果你找到答案,我會很樂意知道。 – Jon 2010-01-21 11:34:16
足夠有趣的配置文件描述了SQL,沒有任何調用需要超過幾個ms。它似乎是應用程序某處的瓶頸:/ – aboutme 2010-01-29 01:46:21