前言

上一篇《ORM增删改查并发性能测试》出现了点小失误,有的输出SQL日志的代码没有禁用,数据库连接字符串可能有问题。统一环境,统一代码后,重新写一篇。

这次重点是并发性能测试,真不是为了diss其它ORM,开始是因为我写的Dapper.LiteSql高并发场景下存在BUG,才写了这个测试,经过修改优化,最好Dapper.LiteSql通过了这个测试。然后Fast.Framework的作者对它的ORM非常自信,我就好奇,是否真的有他说的这么好,口说无凭,我就对它进程各种测试,包括这个高并发测试,刚开始Fast.Framework高并发测试也不通过,后经过作者的优化,就通过了。

测试的现实意义

这两天在对一些ORM进行性能测试(涉及SqlSugar、FreeSql、Fast.Framework、Dapper.LiteSql),测试用的是Winform程序,别人第一眼看到我的程序,说,你这测试没意义!

可能我的测试程序的某些地方写的比较变态吧,但我认为有现实意义,并且网上有相关网站崩溃问题的文章,那什么“爆高分析”,“崩溃问题”,WinDbg用的很6,那写程序阶段为什么没发现呢?

场景

假设WebApi(或者说网站后台服务)正在被高并发访问,一段时间后,服务的线程数量达到了200正常的是类似这样的,任务来了,就干活:及以上,那么.NET的线程池,如果线程处于空闲状态,默认是20秒后释放线程,假设这200多个线程空闲了,但是还没有达到空闲20秒的时间,还没有释放,如果此时,又有大量高并发的访问,200个线程去操作数据库,那就可能很危险了。

关于性能

虽然代码写的可能有点变态,但我的测试不是很严格,也不是很规范。

性能如果不是数量级的差,问题都不大,比如一个是0.8秒,一个是1.8秒,那1.8秒的慢是慢了一点,但问题不大;但如果一个是0.8秒,一个是10秒,那10秒的这个,可能就有点问题了,即使别人用的Emit你用的反射,也不应该差这么多。

当然了,我的测试,数据规模不大,10000条,button可能会点10次,那也才10万数据量,在数据量方面我没有做极端测试,我的重点不是这个,因为很少会去查100万数据到内存中,就暂不讨论这个。

这个测试除了大体上测试一下性能,主要就是增加了并发测试。

非并发性能测试的截图我就不放全了,这几个ORM有差别,但我觉得2秒3秒还是6秒甚至8秒,都问题不大的,都算差不多,都算堪用。

测试环境

数据库及设置

测试数据库是MySQL,版本5.7.28

MySql的连接池大小是1200

测试程序中配置的数据连接字符串

Data Source=localhost;Port=3306;User ID=root;Password=123456;Initial Catalog=xxxxxx_test;Charset=utf8mb4;SslMode=none;Allow User Variables=True;

MySql.Data.dll版本

MySql.Data.dll目前用的是最新的8.0.30版本(题外话,它里面的异步是假异步,把同步方法包装成的异步,我说怎么反而慢了呢,真异步要使用MySqlConnector.dll,Fast.Framework使用的是这个性能很好)。

实体类

以SqlSugar的为例吧,几种ORM测试用的表结构是相同的。

using System;
using System.Linq;
using System.Text;
using SqlSugar; namespace Models
{
///<summary>
///用户表
///</summary>
[SugarTable("sys_user")]
public partial class SysUser
{
public SysUser(){ }
/// <summary>
/// Desc:主键
/// Default:
/// Nullable:False
/// </summary>
[SugarColumn(IsPrimaryKey=true,IsIdentity=true,ColumnName="id")]
public long Id {get;set;} /// <summary>
/// Desc:用户名
/// Default:
/// Nullable:False
/// </summary>
[SugarColumn(ColumnName="user_name")]
public string UserName {get;set;} /// <summary>
/// Desc:用户姓名
/// Default:
/// Nullable:True
/// </summary>
[SugarColumn(ColumnName="real_name")]
public string RealName {get;set;} /// <summary>
/// Desc:用户密码
/// Default:
/// Nullable:False
/// </summary>
[SugarColumn(ColumnName="password")]
public string Password {get;set;} /// <summary>
/// Desc:备注
/// Default:
/// Nullable:True
/// </summary>
[SugarColumn(ColumnName="remark")]
public string Remark {get;set;} /// <summary>
/// Desc:创建者ID
/// Default:
/// Nullable:False
/// </summary>
[SugarColumn(ColumnName="create_userid")]
public string CreateUserid {get;set;} /// <summary>
/// Desc:创建时间
/// Default:
/// Nullable:False
/// </summary>
[SugarColumn(ColumnName="create_time")]
public DateTime CreateTime {get;set;} /// <summary>
/// Desc:更新者ID
/// Default:
/// Nullable:True
/// </summary>
[SugarColumn(ColumnName="update_userid")]
public string UpdateUserid {get;set;} /// <summary>
/// Desc:更新时间
/// Default:
/// Nullable:True
/// </summary>
[SugarColumn(ColumnName="update_time")]
public DateTime? UpdateTime {get;set;} }
}

测试配置及代码

Dapper.LiteSql net461

public class LiteSqlFactory
{
#region 变量
private static ILiteSqlClient _liteSqlClient = new LiteSqlClient("Data Source=localhost;Port=3306;User ID=root;Password=123456;Initial Catalog=litesql_test;Charset=utf8mb4;SslMode=none;Allow User Variables=True;", DBType.MySQL, new MySQLProvider());
#endregion #region 获取 ISession
/// <summary>
/// 获取 ISession
/// </summary>
/// <param name="splitTableMapping">分表映射</param>
public static ISession GetSession(SplitTableMapping splitTableMapping = null)
{
return _liteSqlClient.GetSession(splitTableMapping);
}
#endregion #region 获取 ISession (异步)
/// <summary>
/// 获取 ISession (异步)
/// </summary>
/// <param name="splitTableMapping">分表映射</param>
public static async Task<ISession> GetSessionAsync(SplitTableMapping splitTableMapping = null)
{
return await _liteSqlClient.GetSessionAsync(splitTableMapping);
}
#endregion }
using DAL;
using Dapper.LiteSql;
using Models;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
using Utils; namespace PerformanceTest
{
public partial class Form1 : Form
{
#region 变量
private BsOrderDal m_BsOrderDal = ServiceHelper.Get<BsOrderDal>();
private SysUserDal m_SysUserDal = ServiceHelper.Get<SysUserDal>();
private Random _rnd = new Random();
private int _count = 10000;
private bool _printSql = false;
#endregion #region Form1
public Form1()
{
InitializeComponent();
}
#endregion #region Form1_Load
private void Form1_Load(object sender, EventArgs e)
{
RunTask(() =>
{
LiteSqlFactory.GetSession(); //预热
Log("预热完成");
});
}
#endregion #region Log
private void Log(string log)
{
if (!this.IsDisposed)
{
string msg = DateTime.Now.ToString("mm:ss.fff") + " " + log + "\r\n\r\n"; if (this.InvokeRequired)
{
this.BeginInvoke(new Action(() =>
{
textBox1.AppendText(msg);
}));
}
else
{
textBox1.AppendText(msg);
}
}
}
#endregion #region 清空输出框
private void button10_Click(object sender, EventArgs e)
{
textBox1.Text = string.Empty;
}
#endregion #region RunTask
private Task RunTask(Action action)
{
return Task.Run(() =>
{
try
{
action();
}
catch (Exception ex)
{
Log(ex.ToString());
throw;
}
});
} private Task RunTask<T>(Action<T> action, T t)
{
return Task.Factory.StartNew(obj =>
{
try
{
action((T)obj);
}
catch (Exception ex)
{
Log(ex.ToString());
throw;
}
}, t);
}
#endregion #region cbxPrintSql_Click
private void cbxPrintSql_Click(object sender, EventArgs e)
{
_printSql = cbxPrintSql.Checked;
}
#endregion #region 删除
private void button5_Click(object sender, EventArgs e)
{
RunTask(() =>
{
Log("删除 开始");
var session = LiteSqlFactory.GetSession();
session.CreateSql("id>@Id", 12).DeleteByCondition<SysUser>();
Log("删除 完成");
});
}
#endregion #region 测试批量修改
private void button3_Click(object sender, EventArgs e)
{
RunTask(() =>
{
List<SysUser> userList = m_SysUserDal.GetList("select t.* from sys_user t where t.id > 20"); Log("批量修改 开始 count=" + userList.Count);
DateTime dt = DateTime.Now; var session = LiteSqlFactory.GetSession();
if (_printSql)
{
session.OnExecuting = (s, p) => Console.WriteLine(s); //打印SQL
} try
{
session.AttachOld(userList);
foreach (SysUser user in userList)
{
user.Remark = "测试修改用户" + _rnd.Next(1, 10000);
user.UpdateUserid = "1";
user.UpdateTime = DateTime.Now;
}
userList.ForEach(item => item.UpdateTime = DateTime.Now); session.BeginTransaction();
session.Update(userList);
session.CommitTransaction();
}
catch (Exception ex)
{
session.RollbackTransaction();
throw;
} string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("批量修改 完成,耗时:" + time + "秒");
});
}
#endregion #region 测试批量添加
private void button4_Click(object sender, EventArgs e)
{
RunTask(() =>
{
List<SysUser> userList = new List<SysUser>();
for (int i = 1; i <= _count; i++)
{
SysUser user = new SysUser();
user.UserName = "testUser";
user.RealName = "测试插入用户";
user.Password = "123456";
user.CreateUserid = "1";
user.CreateTime = DateTime.Now;
userList.Add(user);
} Log("批量添加 开始 count=" + userList.Count);
DateTime dt = DateTime.Now; var session = LiteSqlFactory.GetSession();
if (_printSql)
{
session.OnExecuting = (s, p) => Console.WriteLine(s); //打印SQL
} try
{
session.BeginTransaction();
session.Insert(userList);
session.CommitTransaction();
}
catch
{
session.RollbackTransaction();
throw;
} string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("批量添加 完成,耗时:" + time + "秒");
});
}
#endregion #region 测试循环修改
private void button7_Click(object sender, EventArgs e)
{
RunTask(() =>
{
List<SysUser> userList = m_SysUserDal.GetList("select t.* from sys_user t where t.id > 20"); Log("循环修改 开始 count=" + userList.Count);
DateTime dt = DateTime.Now; var session = LiteSqlFactory.GetSession();
if (_printSql)
{
session.OnExecuting = (s, p) => Console.WriteLine(s); //打印SQL
} try
{
session.AttachOld(userList);
foreach (SysUser user in userList)
{
user.Remark = "测试修改用户" + _rnd.Next(1, 10000);
user.UpdateUserid = "1";
user.UpdateTime = DateTime.Now;
} session.BeginTransaction();
foreach (SysUser user in userList)
{
session.Update(user);
}
session.CommitTransaction();
}
catch
{
session.RollbackTransaction();
throw;
} string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("循环修改 完成,耗时:" + time + "秒");
});
}
#endregion #region 测试循环添加
private void button6_Click(object sender, EventArgs e)
{
RunTask(() =>
{
List<SysUser> userList = new List<SysUser>();
for (int i = 1; i <= _count; i++)
{
SysUser user = new SysUser();
user.UserName = "testUser";
user.RealName = "测试插入用户";
user.Password = "123456";
user.CreateUserid = "1";
user.CreateTime = DateTime.Now;
userList.Add(user);
} Log("循环添加 开始 count=" + userList.Count);
DateTime dt = DateTime.Now; var session = LiteSqlFactory.GetSession();
if (_printSql)
{
session.OnExecuting = (s, p) => Console.WriteLine(s); //打印SQL
} try
{
session.BeginTransaction();
foreach (SysUser user in userList)
{
session.Insert(user);
}
session.CommitTransaction();
}
catch
{
session.RollbackTransaction();
throw;
} string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("循环添加 完成,耗时:" + time + "秒");
});
}
#endregion #region 查询
private void button1_Click(object sender, EventArgs e)
{
RunTask(() =>
{
Log("查询 开始");
DateTime dt = DateTime.Now; for (int i = 0; i < 10; i++)
{
var session = LiteSqlFactory.GetSession(); ISqlString sql = session.CreateSql(@"
select t.*
from sys_user t
where t.id > @id
and t.real_name like @remark", 20, "%测试%"); sql.Append(" order by t.create_time desc, t.id asc"); List<SysUser> userList = sql.QueryList<SysUser>();
Log("查询结果 count=" + userList.Count.ToString());
} string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("查询 完成,耗时:" + time + "秒");
});
}
#endregion #region 分页查询
private void button2_Click(object sender, EventArgs e)
{
RunTask(() =>
{
Log("分页查询 开始");
DateTime dt = DateTime.Now; for (int i = 0; i < 10; i++)
{
int total = m_SysUserDal.GetTotalCount();
int pageSize = 100;
int pageCount = (total - 1) / pageSize + 1;
var session = LiteSqlFactory.GetSession(); List<SysUser> userList = new List<SysUser>();
for (int page = 1; page <= pageCount; page++)
{
ISqlString sql = session.CreateSql(@"
select t.*
from sys_user t
where 1=1
and t.id > @id
and t.real_name like @remark", 20, "%测试%"); string orderby = " order by t.create_time desc, t.id asc"; userList.AddRange(sql.QueryPage<SysUser>(orderby, pageSize, page));
}
Log("分页查询结果 count=" + userList.Count.ToString());
} string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("分页查询 完成,耗时:" + time + "秒");
});
}
#endregion #region 并发查询
private void button8_Click(object sender, EventArgs e)
{
ThreadPool.SetMaxThreads(1000, 1000);
ThreadPool.SetMinThreads(200, 200); RunTask(() =>
{
Log("并发查询 开始");
DateTime dt = DateTime.Now; List<Task> tasks = new List<Task>();
for (int i = 1; i <= 1000; i++)
{
int index = i;
Task task = RunTask(() =>
{
var session = LiteSqlFactory.GetSession(); ISqlString sql = session.CreateSql(@"
select t.*
from sys_user t
where t.id > @id
and t.real_name like @remark", 20, "%测试%"); sql.Append(" order by t.create_time desc, t.id asc"); List<SysUser> userList = sql.QueryList<SysUser>();
if (index % 50 == 0) Log("第" + index + "次查询结果 count=" + userList.Count);
});
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray()); string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("并发查询 完成,耗时:" + time + "秒");
});
}
#endregion #region 并发插入
private void button9_Click(object sender, EventArgs e)
{
ThreadPool.SetMaxThreads(1000, 1000);
ThreadPool.SetMinThreads(200, 200); RunTask(() =>
{
List<SysUser> userList = new List<SysUser>();
for (int i = 1; i <= _count; i++)
{
SysUser user = new SysUser();
user.UserName = "testUser";
user.RealName = "测试插入用户";
user.Remark = "测试插入用户" + i;
user.Password = "123456";
user.CreateUserid = "1";
user.CreateTime = DateTime.Now;
userList.Add(user);
} Log("并发插入 开始 count=" + userList.Count);
DateTime dt = DateTime.Now; List<Task> tasks = new List<Task>();
foreach (SysUser item in userList)
{
var task = RunTask(user =>
{
LiteSqlFactory.GetSession().Insert(user);
}, item);
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray()); string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("并发插入 完成,耗时:" + time + "秒");
});
}
#endregion }
}

FreeSql net461

public class FreeSqlUtil
{
#region CreateFreeSqlClient
public static IFreeSql CreateFreeSqlClient()
{
IFreeSql db = new FreeSql.FreeSqlBuilder()
.UseConnectionString(FreeSql.DataType.MySql, @"Data Source=localhost;Port=3306;User ID=root;Password=123456;Initial Catalog=freesql_test;Charset=utf8mb4;SslMode=none;Allow User Variables=True;")
.UseGenerateCommandParameterWithLambda(true)
.Build(); //请务必定义成 Singleton 单例模式 return db;
}
#endregion }
using Models;
using NLog;
using FreeSqlDemo.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using FreeSql.Aop;
using Newtonsoft.Json;
using System.Threading; namespace FreeSqlDemo
{
public partial class Form1 : Form
{
#region 变量
private Logger _log = NLog.LogManager.GetCurrentClassLogger();
private IFreeSql _db;
private int _count = 10000;
private bool _printSql = false;
#endregion #region Form1
public Form1()
{
InitializeComponent();
}
#endregion #region Form1_Load
private void Form1_Load(object sender, EventArgs e)
{
_db = FreeSqlUtil.CreateFreeSqlClient(); if (_printSql)
{
_db.Aop.CurdAfter += CurdAfter;
} RunTask(() =>
{
_db.Queryable<SysUser>().Count(); //预热
Log("预热完成");
});
}
#endregion #region Log
private void Log(string log)
{
if (!this.IsDisposed)
{
string msg = DateTime.Now.ToString("mm:ss.fff") + " " + log + "\r\n\r\n"; if (this.InvokeRequired)
{
this.BeginInvoke(new Action(() =>
{
textBox1.AppendText(msg);
}));
}
else
{
textBox1.AppendText(msg);
}
}
}
#endregion #region 清空输出框
private void button10_Click(object sender, EventArgs e)
{
textBox1.Text = string.Empty;
}
#endregion #region RunTask
private Task RunTask(Action action)
{
return Task.Run(() =>
{
try
{
action();
}
catch (Exception ex)
{
Log(ex.Message + "\r\n" + ex.StackTrace);
}
});
} private Task RunTask<T>(Action<T> action, T t)
{
return Task.Factory.StartNew(obj =>
{
try
{
action((T)obj);
}
catch (Exception ex)
{
Log(ex.ToString());
throw;
}
}, t);
}
#endregion #region 打印SQL
private void CurdAfter(object sender, CurdAfterEventArgs e)
{
if (_printSql)
{
RunTask(() =>
{
string msg = "SQL:" + e.Sql + "\r\nParam:" + JsonConvert.SerializeObject(e.DbParms.ToDictionary(it => it.ParameterName, it => it.Value));
Console.WriteLine(msg);
_log.Debug(msg);
});
}
}
#endregion #region cbxPrintSql_Click
private void cbxPrintSql_Click(object sender, EventArgs e)
{
_printSql = cbxPrintSql.Checked;
}
#endregion #region 生成实体类
private void button1_Click(object sender, EventArgs e)
{
RunTask(() =>
{
Log("开始生成实体类");
Log("生成实体类完成");
});
}
#endregion #region 测试查询
private void button2_Click(object sender, EventArgs e)
{
Log("开始查询");
SysUser conditionModel = new SysUser();
conditionModel.Remark = "管理员";
string remark = "管理员";
List<SysUser> list = _db.Queryable<SysUser>().Where(t => t.Id < 20 && t.Remark.Contains(conditionModel.Remark) && t.CreateTime > new DateTime(2010, 1, 1)).ToList();
foreach (SysUser user in list)
{
Log(string.Format("{0},{1},{2},{3}", user.UserName, user.RealName, user.Remark, user.CreateTime.ToString("yyyy-MM-dd")));
}
Log("查询结束 count=" + list.Count);
}
#endregion #region 测试批量修改
private void button3_Click(object sender, EventArgs e)
{
RunTask(() =>
{
Random rnd = new Random();
List<SysUser> userList = _db.Queryable<SysUser>().Where(t => t.Id > 20).ToList();
Log("批量修改 开始 count=" + userList.Count.ToString("0 000"));
foreach (SysUser user in userList)
{
user.Remark = "测试修改用户" + rnd.Next(0, 10000);
user.UpdateUserid = "1";
user.UpdateTime = DateTime.Now;
} DateTime dt = DateTime.Now; _db.Ado.Transaction(() =>
{
_db.Update<SysUser>().SetSource(userList).ExecuteAffrows();
}); string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("批量修改 完成,耗时:" + time + "秒");
});
}
#endregion #region 测试批量添加
private void button4_Click(object sender, EventArgs e)
{
RunTask(() =>
{
List<SysUser> userList = new List<SysUser>();
for (int i = 1; i <= _count; i++)
{
SysUser user = new SysUser();
user.UserName = "testUser";
user.RealName = "测试插入用户";
user.Password = "123456";
user.CreateUserid = "1";
userList.Add(user);
} Log("批量添加 开始 count=" + userList.Count);
DateTime dt = DateTime.Now; _db.Ado.Transaction(() =>
{
_db.Insert(userList).ExecuteAffrows();
}); string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("批量添加 结束,完成:" + time + "秒");
});
}
#endregion #region 删除
private void button5_Click(object sender, EventArgs e)
{
RunTask(() =>
{
Log("删除 开始");
_db.Delete<SysUser>().Where(t => t.Id > 20).ExecuteAffrows();
Log("删除 完成");
});
}
#endregion #region 测试循环修改
private void button7_Click(object sender, EventArgs e)
{
RunTask(() =>
{
Random rnd = new Random();
List<SysUser> userList = _db.Queryable<SysUser>().Where(t => t.Id > 20).ToList();
Log("循环修改 开始 count=" + userList.Count.ToString("0 000")); DateTime dt = DateTime.Now; _db.Ado.Transaction(() =>
{
var repo = _db.GetRepository<SysUser>(); foreach (SysUser user in userList)
{
repo.Attach(user);
} foreach (SysUser user in userList)
{
user.Remark = "测试修改用户" + rnd.Next(0, 10000);
user.UpdateUserid = "1";
user.UpdateTime = DateTime.Now;
} foreach (SysUser user in userList)
{
repo.Update(user);
}
}); string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("循环修改 完成,耗时:" + time + "秒");
});
}
#endregion #region 测试循环添加
private void button6_Click(object sender, EventArgs e)
{
RunTask(() =>
{
List<SysUser> userList = new List<SysUser>();
for (int i = 1; i <= _count; i++)
{
SysUser user = new SysUser();
user.UserName = "testUser";
user.RealName = "测试插入用户";
user.Password = "123456";
user.CreateUserid = "1";
userList.Add(user);
} Log("循环添加 开始 count=" + userList.Count);
DateTime dt = DateTime.Now; _db.Ado.Transaction(() =>
{
foreach (SysUser user in userList)
{
_db.Insert(user).ExecuteIdentity();
}
}); string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("循环添加 完成,耗时:" + time + "秒");
});
}
#endregion #region 查询
private void button9_Click(object sender, EventArgs e)
{
RunTask(() =>
{
_db.Queryable<SysUser>().Where(t => t.Id == 1).ToList(); //预热 Log("查询 开始");
DateTime dt = DateTime.Now; for (int i = 0; i < 10; i++)
{
List<SysUser> userList = _db.Queryable<SysUser>().Where(t => t.Id > 20 && t.RealName.Contains("测试")).OrderByDescending(t => t.CreateTime).OrderBy(t => t.Id).ToList();
Log("查询结果 count=" + userList.Count.ToString());
} string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("查询 完成,耗时:" + time + "秒");
});
}
#endregion #region 分页查询
private void button8_Click(object sender, EventArgs e)
{
RunTask(() =>
{
_db.Queryable<SysUser>().Where(t => t.Id == 1).ToList(); //预热 Log("分页查询 开始");
DateTime dt = DateTime.Now; for (int i = 0; i < 10; i++)
{
long total = _db.Queryable<SysUser>().Count();
int pageSize = 100;
int pageCount = (int)((total - 1) / pageSize + 1);
List<SysUser> userList = new List<SysUser>();
for (int page = 1; page <= pageCount; page++)
{
userList.AddRange(_db.Queryable<SysUser>().Where(t => t.Id > 20 && t.RealName.Contains("测试")).OrderByDescending(t => t.CreateTime).OrderBy(t => t.Id).Page(page, pageSize).ToList());
}
Log("分页查询结果 count=" + userList.Count.ToString());
} string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("分页查询 完成,耗时:" + time + "秒");
});
}
#endregion #region 并发查询
private void button11_Click(object sender, EventArgs e)
{
ThreadPool.SetMaxThreads(1000, 1000);
ThreadPool.SetMinThreads(200, 200); RunTask(() =>
{
Log("并发查询 开始");
DateTime dt = DateTime.Now; List<Task> tasks = new List<Task>();
for (int i = 1; i <= 1000; i++)
{
int index = i;
Task task = RunTask(() =>
{
List<SysUser> userList = _db.Queryable<SysUser>()
.Where(t => t.Id > 20 && t.RealName.Contains("测试"))
.OrderByDescending(t => t.CreateTime).OrderBy(t => t.Id).ToList();
if (index % 50 == 0) Log("第" + index + "次查询结果 count=" + userList.Count);
});
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray()); string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("并发查询 完成,耗时:" + time + "秒");
});
}
#endregion #region 并发插入
private void button12_Click(object sender, EventArgs e)
{
ThreadPool.SetMaxThreads(1000, 1000);
ThreadPool.SetMinThreads(200, 200); RunTask(() =>
{
List<SysUser> userList = new List<SysUser>();
for (int i = 1; i <= _count; i++)
{
SysUser user = new SysUser();
user.UserName = "testUser";
user.RealName = "测试插入用户";
user.Remark = "测试插入用户" + i;
user.Password = "123456";
user.CreateUserid = "1";
user.CreateTime = DateTime.Now;
userList.Add(user);
} Log("并发插入 开始 count=" + userList.Count);
DateTime dt = DateTime.Now; List<Task> tasks = new List<Task>();
foreach (SysUser item in userList)
{
var task = RunTask(user =>
{
_db.Insert(user).ExecuteIdentity();
}, item);
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray()); string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("并发插入 完成,耗时:" + time + "秒");
});
}
#endregion }
}

SqlSugar net461

public class SqlSugarUtil
{
public static readonly string ConnectionString = "Data Source=localhost;Port=3306;User ID=root;Password=123456;Initial Catalog=sqlsugar_test;Charset=utf8mb4;SslMode=none;Allow User Variables=True;"; #region CreateSqlSugarClient
public static SqlSugarScope CreateSqlSugarClient()
{
SqlSugarScope db = new SqlSugarScope(new ConnectionConfig()
{
ConnectionString = ConnectionString,//连接符字串
DbType = SqlSugar.DbType.MySql, //数据库类型
IsAutoCloseConnection = true //不设成true要手动close
}); return db;
}
#endregion #region CreateModels 生成实体类
/// <summary>
/// 生成实体类
/// </summary>
public static void CreateModels(SqlSugarClient db, string tableName = null)
{
......此处省略
}
#endregion }
using Models;
using NLog;
using SqlSugar;
using SqlSugarDemo.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms; namespace SqlSugarDemo
{
public partial class Form1 : Form
{
#region 变量
private Logger _log = NLog.LogManager.GetCurrentClassLogger();
private SqlSugarScope _db;
private int _count = 10000;
private bool _printSql = false;
#endregion #region Form1
public Form1()
{
InitializeComponent();
}
#endregion #region Form1_Load
private void Form1_Load(object sender, EventArgs e)
{
_db = SqlSugarUtil.CreateSqlSugarClient(); if (_printSql)
{
_db.Aop.OnLogExecuting = OnLogExecuting;
} RunTask(() =>
{
_db.Queryable<SysUser>().Count(); //预热
Log("预热完成");
});
}
#endregion #region Log
private void Log(string log)
{
if (!this.IsDisposed)
{
string msg = DateTime.Now.ToString("mm:ss.fff") + " " + log + "\r\n\r\n"; if (this.InvokeRequired)
{
this.BeginInvoke(new Action(() =>
{
textBox1.AppendText(msg);
}));
}
else
{
textBox1.AppendText(msg);
}
}
}
#endregion #region 清空输出框
private void button10_Click(object sender, EventArgs e)
{
textBox1.Text = string.Empty;
}
#endregion #region RunTask
private Task RunTask(Action action)
{
return Task.Run(() =>
{
try
{
action();
}
catch (Exception ex)
{
Log(ex.Message + "\r\n" + ex.StackTrace);
}
});
} private Task RunTask<T>(Action<T> action, T t)
{
return Task.Factory.StartNew(obj =>
{
try
{
action((T)obj);
}
catch (Exception ex)
{
Log(ex.ToString());
}
}, t);
}
#endregion #region cbxPrintSql_Click
private void cbxPrintSql_CheckedChanged(object sender, EventArgs e)
{
_printSql = cbxPrintSql.Checked;
}
#endregion #region 打印SQL
private void OnLogExecuting(string sql, SugarParameter[] paramArr)
{
if (_printSql)
{
RunTask(() =>
{
//string msg = "SQL:" + sql + "\r\nParam:" + _db.Utilities.SerializeObject(paramArr.ToDictionary(it => it.ParameterName, it => it.Value));
Console.WriteLine(sql);
_log.Debug(sql);
});
}
}
#endregion #region 生成实体类
private void button1_Click(object sender, EventArgs e)
{
RunTask(() =>
{
Log("开始生成实体类");
SqlSugarUtil.CreateModels(new SqlSugarClient(new ConnectionConfig()
{
ConnectionString = SqlSugarUtil.ConnectionString,//连接符字串
DbType = SqlSugar.DbType.MySql, //数据库类型
IsAutoCloseConnection = true //不设成true要手动close
}));
Log("生成实体类完成");
});
}
#endregion #region 测试查询
private void button2_Click(object sender, EventArgs e)
{
Log("开始查询");
SysUser conditionModel = new SysUser();
conditionModel.Remark = "管理员";
string remark = "管理员";
List<SysUser> list = _db.Queryable<SysUser>().Where(t => t.Id < 20 && t.Remark.Contains(conditionModel.Remark) && t.CreateTime > new DateTime(2010, 1, 1)).ToList();
foreach (SysUser user in list)
{
Log(string.Format("{0},{1},{2},{3}", user.UserName, user.RealName, user.Remark, user.CreateTime.ToString("yyyy-MM-dd")));
}
Log("查询结束 count=" + list.Count);
}
#endregion #region 测试批量修改
private void button3_Click(object sender, EventArgs e)
{
RunTask(() =>
{
Random rnd = new Random();
List<SysUser> userList = _db.Queryable<SysUser>().Where(t => t.Id > 20).ToList();
Log("批量修改 开始 count=" + userList.Count.ToString("0 000"));
foreach (SysUser user in userList)
{
user.Remark = "测试修改用户" + rnd.Next(0, 10000);
user.UpdateUserid = "1";
user.UpdateTime = DateTime.Now;
} DateTime dt = DateTime.Now;
try
{
_db.Ado.BeginTran();
_db.Updateable(userList).ExecuteCommand();
_db.Ado.CommitTran();
}
catch (Exception ex)
{
_db.Ado.RollbackTran();
throw ex;
}
string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("批量修改 完成,耗时:" + time + "秒");
});
}
#endregion #region 测试批量添加
private void button4_Click(object sender, EventArgs e)
{
RunTask(() =>
{
List<SysUser> userList = new List<SysUser>();
for (int i = 1; i <= _count; i++)
{
SysUser user = new SysUser();
user.UserName = "testUser";
user.RealName = "测试插入用户";
user.Password = "123456";
user.CreateUserid = "1";
userList.Add(user);
} Log("批量添加 开始 count=" + userList.Count);
DateTime dt = DateTime.Now;
try
{
_db.Ado.BeginTran();
_db.Insertable(userList).ExecuteCommand();
_db.Ado.CommitTran();
}
catch (Exception ex)
{
_db.Ado.RollbackTran();
throw ex;
}
string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("批量添加 结束,完成:" + time + "秒");
});
}
#endregion #region 删除
private void button5_Click(object sender, EventArgs e)
{
RunTask(() =>
{
Log("删除 开始");
_db.Deleteable<SysUser>(t => t.Id > 20).ExecuteCommand();
Log("删除 完成");
});
}
#endregion #region 测试循环修改
private void button7_Click(object sender, EventArgs e)
{
RunTask(() =>
{
Random rnd = new Random();
List<SysUser> userList = _db.Queryable<SysUser>().Where(t => t.Id > 20).ToList();
Log("循环修改 开始 count=" + userList.Count.ToString("0 000"));
foreach (SysUser user in userList)
{
user.Remark = "测试修改用户" + rnd.Next(0, 10000);
user.UpdateUserid = "1";
user.UpdateTime = DateTime.Now;
} DateTime dt = DateTime.Now;
try
{
_db.Ado.BeginTran();
foreach (SysUser user in userList)
{
_db.Updateable(user).ExecuteCommand();
}
_db.Ado.CommitTran();
}
catch (Exception ex)
{
_db.Ado.RollbackTran();
throw ex;
}
string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("循环修改 完成,耗时:" + time + "秒");
});
}
#endregion #region 测试循环添加
private void button6_Click(object sender, EventArgs e)
{
RunTask(() =>
{
List<SysUser> userList = new List<SysUser>();
for (int i = 1; i <= _count; i++)
{
SysUser user = new SysUser();
user.UserName = "testUser";
user.RealName = "测试插入用户";
user.Password = "123456";
user.CreateUserid = "1";
userList.Add(user);
} Log("循环添加 开始 count=" + userList.Count);
DateTime dt = DateTime.Now;
try
{
_db.Ado.BeginTran();
foreach (SysUser user in userList)
{
_db.Insertable(user).ExecuteCommand();
}
_db.Ado.CommitTran();
}
catch (Exception ex)
{
_db.Ado.RollbackTran();
throw ex;
}
string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("循环添加 完成,耗时:" + time + "秒");
});
}
#endregion #region 查询
private void button9_Click(object sender, EventArgs e)
{
RunTask(() =>
{
_db.Queryable<SysUser>().Where(t => t.Id == 1).ToList(); //预热 Log("查询 开始");
DateTime dt = DateTime.Now; for (int i = 0; i < 10; i++)
{
List<SysUser> userList = _db.Queryable<SysUser>().Where(t => t.Id > 20 && t.RealName.Contains("测试")).OrderBy(t => t.CreateTime, OrderByType.Desc).OrderBy(t => t.Id).ToList();
Log("查询结果 count=" + userList.Count.ToString());
} string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("查询 完成,耗时:" + time + "秒");
});
}
#endregion #region 分页查询
private void button8_Click(object sender, EventArgs e)
{
RunTask(() =>
{
_db.Queryable<SysUser>().Where(t => t.Id == 1).ToList(); //预热 Log("分页查询 开始");
DateTime dt = DateTime.Now; for (int i = 0; i < 10; i++)
{
int total = _db.Queryable<SysUser>().Count();
int pageSize = 100;
int pageCount = (total - 1) / pageSize + 1;
List<SysUser> userList = new List<SysUser>();
for (int page = 1; page <= pageCount; page++)
{
userList.AddRange(_db.Queryable<SysUser>().Where(t => t.Id > 20 && t.RealName.Contains("测试")).OrderBy(t => t.CreateTime, OrderByType.Desc).OrderBy(t => t.Id).ToPageList(page, pageSize));
}
Log("分页查询结果 count=" + userList.Count.ToString());
} string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("分页查询 完成,耗时:" + time + "秒");
});
}
#endregion #region 并发查询
private void button11_Click(object sender, EventArgs e)
{
ThreadPool.SetMaxThreads(1000, 1000);
ThreadPool.SetMinThreads(200, 200); RunTask(() =>
{
Log("并发查询 开始");
DateTime dt = DateTime.Now; List<Task> tasks = new List<Task>();
for (int i = 1; i <= 1000; i++)
{
int index = i;
Task task = RunTask(() =>
{
List<SysUser> userList = _db.Queryable<SysUser>().Where(t => t.Id > 20 && t.RealName.Contains("测试")).OrderBy(t => t.CreateTime, OrderByType.Desc).OrderBy(t => t.Id).ToList();
if (index % 50 == 0) Log("第" + index + "次查询结果 count=" + userList.Count);
});
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray()); string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("并发查询 完成,耗时:" + time + "秒");
});
}
#endregion #region 并发插入
private void button12_Click(object sender, EventArgs e)
{
ThreadPool.SetMaxThreads(1000, 1000);
ThreadPool.SetMinThreads(200, 200); RunTask(() =>
{
List<SysUser> userList = new List<SysUser>();
for (int i = 1; i <= _count; i++)
{
SysUser user = new SysUser();
user.UserName = "testUser";
user.RealName = "测试插入用户";
user.Remark = "测试插入用户" + i;
user.Password = "123456";
user.CreateUserid = "1";
user.CreateTime = DateTime.Now;
userList.Add(user);
} Log("并发插入 开始 count=" + userList.Count);
DateTime dt = DateTime.Now; List<Task> tasks = new List<Task>();
foreach (SysUser item in userList)
{
var task = RunTask(user =>
{
_db.Insertable(user).ExecuteCommand();
}, item);
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray()); string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("并发插入 完成,耗时:" + time + "秒");
});
}
#endregion }
}

Fast.Framework net6

using Fast.Framework;
using Fast.Framework.Interfaces;
using Fast.Framework.Models;
using Fast.Framework.Extensions;
using Fast.Framework.Aop;
using Models; namespace FastFrameworkDemo
{
public partial class Form1 : Form
{
#region 变量
private Random _rnd = new Random();
private int _count = 10000;
private bool _printSql = false;
#endregion #region Form1
public Form1()
{
InitializeComponent();
}
#endregion #region Form1_Load
private void Form1_Load(object sender, EventArgs e)
{
RunTask(async () =>
{
await GetDbContext().Query<SysUser>().CountAsync();
Log("预热完成");
});
}
#endregion #region Log
private void Log(string log)
{
if (!this.IsDisposed)
{
string msg = DateTime.Now.ToString("mm:ss.fff") + " " + log + "\r\n\r\n"; if (this.InvokeRequired)
{
this.BeginInvoke(new Action(() =>
{
textBox1.AppendText(msg);
}));
}
else
{
textBox1.AppendText(msg);
}
}
}
#endregion #region 清空输出框
private void button10_Click(object sender, EventArgs e)
{
textBox1.Text = string.Empty;
}
#endregion #region RunTask
private Task RunTask(Action action)
{
return Task.Run(() =>
{
try
{
action();
}
catch (Exception ex)
{
Log(ex.ToString());
}
});
} private Task RunTask<T>(Action<T> action, T t)
{
return Task.Factory.StartNew(obj =>
{
try
{
action((T)obj);
}
catch (Exception ex)
{
Log(ex.ToString());
}
}, t);
}
#endregion #region cbxPrintSql_Click
private void cbxPrintSql_Click(object sender, EventArgs e)
{
_printSql = cbxPrintSql.Checked;
}
#endregion #region GetDbContext
private IDbContext GetDbContext()
{
IDbContext _db = new DbContext(new List<DbOptions>() {
new DbOptions()
{
DbId = "1",
DbType = DbType.MySQL,
ProviderName = "MySqlConnector",
FactoryName = "MySqlConnector.MySqlConnectorFactory,MySqlConnector",
ConnectionStrings = "Data Source=localhost;Port=3306;User ID=root;Password=123456;Initial Catalog=fast_framework_test;Charset=utf8mb4;SslMode=none;Allow User Variables=True;"
}
}); if (_printSql)
{
_db.Aop.DbLog = (sql, dp) =>
{
Console.WriteLine($"执行Sql:{sql}");
if (dp != null)
{
foreach (var item in dp)
{
Console.WriteLine($"参数名称:{item.ParameterName} 参数值:{item.Value}");
}
}
};
} return _db;
}
#endregion #region 删除
private void button1_Click(object sender, EventArgs e)
{
RunTask(async () =>
{
Log("删除 开始");
await GetDbContext().Delete<SysUser>().Where(t => t.Id > 20).ExceuteAsync();
Log("删除 完成");
});
}
#endregion #region 批量修改
private void button2_Click(object sender, EventArgs e)
{
RunTask(async () =>
{
List<SysUser> userList = await GetDbContext().Query<SysUser>().Where(t => t.Id > 20).ToListAsync(); Log("批量修改 开始 count=" + userList.Count);
DateTime dt = DateTime.Now; try
{
foreach (SysUser user in userList)
{
user.Remark = "测试修改用户" + _rnd.Next(1, 10000);
user.UpdateUserid = "1";
user.UpdateTime = DateTime.Now;
} await GetDbContext().Update(userList).ExceuteAsync();
}
catch
{
//todo:没有rollback?
throw;
} string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("批量修改 完成,耗时:" + time + "秒");
});
}
#endregion #region 批量添加
private void button3_Click(object sender, EventArgs e)
{
RunTask(async () =>
{
List<SysUser> userList = new List<SysUser>();
for (int i = 1; i <= _count; i++)
{
SysUser user = new SysUser();
user.UserName = "testUser";
user.RealName = "测试插入用户";
user.Password = "123456";
user.CreateUserid = "1";
user.CreateTime = DateTime.Now;
userList.Add(user);
} Log("批量添加 开始 count=" + userList.Count);
DateTime dt = DateTime.Now; try
{
await GetDbContext().Insert(userList).ExceuteAsync();
}
catch
{
//todo:没有rollback?
throw;
} string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("批量添加 完成,耗时:" + time + "秒");
});
}
#endregion #region 循环修改
private void button4_Click(object sender, EventArgs e)
{
RunTask(async () =>
{
List<SysUser> userList = await GetDbContext().Query<SysUser>().Where(t => t.Id > 20).ToListAsync(); Log("循环修改 开始 count=" + userList.Count);
DateTime dt = DateTime.Now; try
{
foreach (SysUser user in userList)
{
user.Remark = "测试修改用户" + _rnd.Next(1, 10000);
user.UpdateUserid = "1";
user.UpdateTime = DateTime.Now;
} var db = GetDbContext();
await db.Ado.BeginTranAsync();
foreach (SysUser user in userList)
{
await db.Update(user).ExceuteAsync();
}
await db.Ado.CommitTranAsync();
}
catch
{
//todo:没有rollback?
throw;
} string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("循环修改 完成,耗时:" + time + "秒");
});
}
#endregion #region 循环添加
private void button5_Click(object sender, EventArgs e)
{
RunTask(async () =>
{
List<SysUser> userList = new List<SysUser>();
for (int i = 1; i <= _count; i++)
{
SysUser user = new SysUser();
user.UserName = "testUser";
user.RealName = "测试插入用户";
user.Password = "123456";
user.CreateUserid = "1";
user.CreateTime = DateTime.Now;
userList.Add(user);
} Log("循环添加 开始 count=" + userList.Count);
DateTime dt = DateTime.Now; try
{
var db = GetDbContext();
await db.Ado.BeginTranAsync();
foreach (SysUser user in userList)
{
await db.Insert(user).ExceuteAsync();
}
await db.Ado.CommitTranAsync();
}
catch
{
//todo:没有rollback?
throw;
} string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("循环添加 完成,耗时:" + time + "秒");
});
}
#endregion #region 查询
private void button6_Click(object sender, EventArgs e)
{
RunTask(async () =>
{
Log("查询 开始");
DateTime dt = DateTime.Now; var db = GetDbContext();
for (int i = 0; i < 10; i++)
{
List<SysUser> userList = await db.Query<SysUser>()
.Where(t => t.Id > 20 && t.RealName.Contains("%测试%"))
.OrderBy("create_time", "desc")
.OrderBy("id", "asc").ToListAsync();
Log("查询结果 count=" + userList.Count.ToString());
} string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("查询 完成,耗时:" + time + "秒");
});
}
#endregion #region 分页查询
private void button7_Click(object sender, EventArgs e)
{
Log("尚未实现");
}
#endregion #region 并发查询
private void button8_Click(object sender, EventArgs e)
{
RunTask(() =>
{
ThreadPool.SetMaxThreads(1000, 1000);
ThreadPool.SetMinThreads(200, 200); Log("并发查询 开始");
DateTime dt = DateTime.Now; List<Task> tasks = new List<Task>();
for (int i = 1; i <= 1000; i++)
{
int index = i;
Task task = RunTask(async () =>
{
List<SysUser> userList = await GetDbContext().Query<SysUser>()
.Where(t => t.Id > 20 && t.RealName.Contains("%测试%"))
.OrderBy("create_time", "desc")
.OrderBy("id", "asc").ToListAsync();
if (index % 50 == 0) Log("第" + index + "次查询结果 count=" + userList.Count);
});
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray()); string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("并发查询 完成,耗时:" + time + "秒");
});
}
#endregion #region 并发插入
private void button9_Click(object sender, EventArgs e)
{
RunTask(() =>
{
ThreadPool.SetMaxThreads(1000, 1000);
ThreadPool.SetMinThreads(200, 200); List<SysUser> userList = new List<SysUser>();
for (int i = 1; i <= _count; i++)
{
SysUser user = new SysUser();
user.UserName = "testUser";
user.RealName = "测试插入用户";
user.Remark = "测试插入用户" + i;
user.Password = "123456";
user.CreateUserid = "1";
user.CreateTime = DateTime.Now;
userList.Add(user);
} Log("并发插入 开始 count=" + userList.Count);
DateTime dt = DateTime.Now; List<Task> tasks = new List<Task>();
foreach (SysUser item in userList)
{
var task = RunTask(async user =>
{
await GetDbContext().Insert(user).ExceuteAsync();
}, item);
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray()); string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("并发插入 完成,耗时:" + time + "秒");
});
}
#endregion }
}

Dapper.LiteSql net6

using Dapper.LiteSql;
using Models;
using Provider; namespace DapperLiteSqlDemo
{
public partial class Form1 : Form
{
#region 变量
private Random _rnd = new Random();
private int _count = 10000;
private bool _showSqlLog = false;
private ILiteSqlClient _db;
private bool _printSql = false;
#endregion #region Form1
public Form1()
{
InitializeComponent();
}
#endregion #region Form1_Load
private void Form1_Load(object sender, EventArgs e)
{
_db = new LiteSqlClient("Data Source=localhost;Port=3306;User ID=root;Password=123456;Initial Catalog=litesql_test;Charset=utf8mb4;SslMode=none;Allow User Variables=True;",
DBType.MySQL, new MySQLProvider()); RunTask(() =>
{
_db.GetSession(); //预热
Log("预热完成");
});
}
#endregion #region Log
private void Log(string log)
{
if (!this.IsDisposed)
{
string msg = DateTime.Now.ToString("mm:ss.fff") + " " + log + "\r\n\r\n"; if (this.InvokeRequired)
{
this.BeginInvoke(new Action(() =>
{
textBox1.AppendText(msg);
}));
}
else
{
textBox1.AppendText(msg);
}
}
}
#endregion #region 清空输出框
private void button10_Click(object sender, EventArgs e)
{
textBox1.Text = string.Empty;
}
#endregion #region RunTask
private Task RunTask(Action action)
{
return Task.Run(() =>
{
try
{
action();
}
catch (Exception ex)
{
Log(ex.ToString());
throw;
}
});
} private Task RunTask<T>(Action<T> action, T t)
{
return Task.Factory.StartNew(obj =>
{
try
{
action((T)obj);
}
catch (Exception ex)
{
Log(ex.ToString());
throw;
}
}, t);
}
#endregion #region cbxPrintSql_Click
private void cbxPrintSql_Click(object sender, EventArgs e)
{
_printSql = cbxPrintSql.Checked;
}
#endregion #region 删除
private void button1_Click(object sender, EventArgs e)
{
RunTask(async () =>
{
Log("删除 开始");
await _db.GetSession().CreateSql("id>@Id", 20).DeleteByConditionAsync<SysUser>();
Log("删除 完成");
});
}
#endregion #region 批量修改
private void button2_Click(object sender, EventArgs e)
{
RunTask(async () =>
{
List<SysUser> userList = await _db.GetSession().Queryable<SysUser>().Where(t => t.Id > 20).ToListAsync(); Log("批量修改 开始 count=" + userList.Count);
DateTime dt = DateTime.Now;
ISession? session = null; try
{
foreach (SysUser user in userList)
{
user.Remark = "测试修改用户" + _rnd.Next(1, 10000);
user.UpdateUserid = "1";
user.UpdateTime = DateTime.Now;
} session = await _db.GetSessionAsync();
session.BeginTransaction();
await session.UpdateAsync(userList);
session.CommitTransaction();
}
catch
{
session?.RollbackTransaction();
throw;
} string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("批量修改 完成,耗时:" + time + "秒");
});
}
#endregion #region 批量添加
private void button3_Click(object sender, EventArgs e)
{
RunTask(async () =>
{
List<SysUser> userList = new List<SysUser>();
for (int i = 1; i <= _count; i++)
{
SysUser user = new SysUser();
user.UserName = "testUser";
user.RealName = "测试插入用户";
user.Password = "123456";
user.CreateUserid = "1";
user.CreateTime = DateTime.Now;
userList.Add(user);
} Log("批量添加 开始 count=" + userList.Count);
DateTime dt = DateTime.Now;
ISession? session = null; try
{ session = await _db.GetSessionAsync();
session.BeginTransaction();
await session.InsertAsync(userList);
session.CommitTransaction();
}
catch
{
session?.RollbackTransaction();
throw;
} string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("批量添加 完成,耗时:" + time + "秒");
});
}
#endregion #region 循环修改
private void button4_Click(object sender, EventArgs e)
{
RunTask(async () =>
{
List<SysUser> userList = await _db.GetSession().Queryable<SysUser>().Where(t => t.Id > 20).ToListAsync(); Log("循环修改 开始 count=" + userList.Count);
DateTime dt = DateTime.Now;
ISession? session = null; try
{
foreach (SysUser user in userList)
{
user.Remark = "测试修改用户" + _rnd.Next(1, 10000);
user.UpdateUserid = "1";
user.UpdateTime = DateTime.Now;
} session = await _db.GetSessionAsync();
session.BeginTransaction();
foreach (SysUser user in userList)
{
await session.UpdateAsync(user);
}
session.CommitTransaction();
}
catch
{
session?.RollbackTransaction();
throw;
} string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("循环修改 完成,耗时:" + time + "秒");
});
}
#endregion #region 循环添加
private void button5_Click(object sender, EventArgs e)
{
RunTask(async () =>
{
List<SysUser> userList = new List<SysUser>();
for (int i = 1; i <= _count; i++)
{
SysUser user = new SysUser();
user.UserName = "testUser";
user.RealName = "测试插入用户";
user.Password = "123456";
user.CreateUserid = "1";
user.CreateTime = DateTime.Now;
userList.Add(user);
} Log("循环添加 开始 count=" + userList.Count);
DateTime dt = DateTime.Now;
ISession? session = null; try
{ session = await _db.GetSessionAsync();
session.BeginTransaction();
foreach (SysUser user in userList)
{
await session.InsertAsync(user);
}
session.CommitTransaction();
}
catch
{
session?.RollbackTransaction();
throw;
} string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("循环添加 完成,耗时:" + time + "秒");
});
}
#endregion #region 查询
private void button6_Click(object sender, EventArgs e)
{
RunTask(async () =>
{
Log("查询 开始");
DateTime dt = DateTime.Now; for (int i = 0; i < 10; i++)
{
List<SysUser> userList = await _db.GetSession().Queryable<SysUser>()
.Where(t => t.Id > 20 && t.RealName.Contains("%测试%"))
.OrderByDescending(t => t.CreateTime)
.OrderBy(t => t.Id).ToListAsync();
Log("查询结果 count=" + userList.Count.ToString());
} string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("查询 完成,耗时:" + time + "秒");
});
}
#endregion #region 分页查询
private void button7_Click(object sender, EventArgs e)
{
Log("尚未实现");
}
#endregion #region 并发查询
private void button8_Click(object sender, EventArgs e)
{
RunTask(() =>
{
ThreadPool.SetMaxThreads(1000, 1000);
ThreadPool.SetMinThreads(200, 200); Log("并发查询 开始");
DateTime dt = DateTime.Now; List<Task> tasks = new List<Task>();
for (int i = 1; i <= 1000; i++)
{
int index = i;
Task task = RunTask(async () =>
{
List<SysUser> userList = await _db.GetSession().Queryable<SysUser>()
.Where(t => t.Id > 20 && t.RealName.Contains("%测试%"))
.OrderByDescending(t => t.CreateTime)
.OrderBy(t => t.Id).ToListAsync();
if (index % 50 == 0) Log("第" + index + "次查询结果 count=" + userList.Count);
});
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray()); string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("并发查询 完成,耗时:" + time + "秒");
});
}
#endregion #region 并发插入
private void button9_Click(object sender, EventArgs e)
{
RunTask(() =>
{
ThreadPool.SetMaxThreads(1000, 1000);
ThreadPool.SetMinThreads(200, 200); List<SysUser> userList = new List<SysUser>();
for (int i = 1; i <= _count; i++)
{
SysUser user = new SysUser();
user.UserName = "testUser";
user.RealName = "测试插入用户";
user.Remark = "测试插入用户" + i;
user.Password = "123456";
user.CreateUserid = "1";
user.CreateTime = DateTime.Now;
userList.Add(user);
} Log("并发插入 开始 count=" + userList.Count);
DateTime dt = DateTime.Now; List<Task> tasks = new List<Task>();
foreach (SysUser item in userList)
{
var task = RunTask(async user =>
{
await _db.GetSession().InsertAsync(user);
}, item);
tasks.Add(task);
}
Task.WaitAll(tasks.ToArray()); string time = DateTime.Now.Subtract(dt).TotalSeconds.ToString("0.000");
Log("并发插入 完成,耗时:" + time + "秒");
});
}
#endregion }
}

测试结果

常规测试

Dapper.LiteSql net461

FreeSql net461

SqlSugar net461

Fast.Framework net6

除了MySql.Data.dll还引用了MySqlConnector.dll (为什么net6?它不支持net framework)

Dapper.LiteSql net6

并发查询

Dapper.LiteSql net461

FreeSql net461

SqlSugar net461

Fast.Framework net6

除了MySql.Data.dll还引用了MySqlConnector.dll (为什么net6?它不支持net framework,环境不同,所以这个测试结果供参考,就不要计较了)

Dapper.LiteSql net6

(为了和Fast.Framework对比,确实慢,慢70%左右,可能是MySqlConnector.dll的功劳,它是真异步,只用MySql.Data.dll是假异步)

并发插入

Dapper.LiteSql net461

FreeSql net461

SqlSugar net461

Fast.Framework net6

除了MySql.Data.dll还引用了MySqlConnector.dll (为什么net6?它不支持net framework)

Dapper.LiteSql net6

(为了和Fast.Framework对比)

ORM增删改查并发性能测试2的更多相关文章

  1. ORM增删改查并发性能测试

    这两天在对一些ORM进行性能测试(涉及SqlSugar.FreeSql.Fast.Framework.Dapper.LiteSql),测试用的是Winform程序,别人第一眼看到我的程序,说,你这测试 ...

  2. Django框架(三)—— orm增删改查、Django生命周期

    目录 orm增删改查.Django生命周期 一.orm介绍 二.orm增删改字段 三.Django生命周期 orm增删改查.Django生命周期 一.orm介绍 1.什么是orm ORM即Object ...

  3. 饮冰三年-人工智能-Python-24 Django ORM增删改查

    一:首先使用默认的sqlite3创建表 1:现在在models.py中添加表模型 from django.db import models # Create your models here. cla ...

  4. day054 组件 CBV FBV 装饰器 ORM增删改查

    组件: ​ 把一小段HTML 放在一个HTML中 nav.html ​ 使用: ​ {% include ‘nav.html ’ %} 一. FBV 和CBV 1.FBV(function base ...

  5. beego 初体验 - orm - 增删改查

    本文记录一下 beego orm 简单的增删改查,大牛请绕道. 首先,注册4个增删改查的路由: 其次,在 views 文件夹下增加对应的模板(页面): controller 类里写上增删改查的方法: ...

  6. django ORM 增删改查 模糊查询 字段类型 及参数等

    ORM 相关 #sql中的表 #创建表: CREATE TABLE employee( id INT PRIMARY KEY auto_increment , name VARCHAR (), gen ...

  7. ORM增删改查

    目录 orm django 连接mysql顺序 1 settings配置文件中 2 项目文件夹下的init文件中写上下面内容, 补充 3 models文件中创建一个类(类名就是表名) 4.执行数据库同 ...

  8. Django 自带的ORM增删改查

     通过Django来对数据库进行增删改查 1 首先创建类,在app应用程序里面的model模块里面创建类,写好数据库信息,方便我们待会初始化: 2 创建在django项目里面的settings里面添加 ...

  9. Django框架(三)-- orm增删改查、Django生命周期

    一.orm介绍 1.什么是orm ORM即Object Relational Mapping,全称对象关系映射. 2.使用orm的优缺点 优点: 不用写SQL语句 开发效率高 缺点: SQL的效率低 ...

随机推荐

  1. UiPathExcel读取操作

    一.Uipath操作Excel的相关基本概念 1.UiPath操作Excel的两组方法 App Integration > Excel   VS  System > File > W ...

  2. Nginx防御CC攻击

    CC攻击可以归为DDoS攻击的一种.他们之间都原理都是一样的,即发送大量的请求数据来导致服务器拒绝服务,是一种连接攻击.CC攻击又可分为代理CC攻击,和肉鸡CC攻击.代理CC攻击是黑客借助代理服务器生 ...

  3. 集合-list常用方法总结

    每个方法使用见下方代码详解 点击查看代码 ArrayList list = new ArrayList(); list.add("AA"); list.add(123); list ...

  4. 2022-7-15 java 数据结构入门

    @ 目录 数据结构 1.二分查找 动图演示: 2.冒泡排序 1.冒泡排序原理 2.冒泡排序基础版 3.冒泡排序代码优化版 4.冒泡排序代码升级版 3.选择排序 1. 算法步骤 2.插入排序图解: 3. ...

  5. 绿色安装MySQL5.7版本----配置my.ini文件注意事项

    前言 由于前段时间电脑重装,虽然很多软件不在C盘,但是由于很多注册表以及关联文件被删除,很多软件还需要重新配置甚至卸载重装. 使用MySQL时就遇到了这种情况,在修改配置文件无效的情况下选择了重新安装 ...

  6. C++指针和结构体基础知识

    学习C++首先要回忆起C语言当中的指针和结构体知识,本文作者将通过一段代码来总结指针和结构体基础知识:指针是一个变量,其值为另一个变量的地址,即,内存位置的直接地址.就像其他变量或常量一样,您必须在使 ...

  7. logrotate command in Linux

    背景 在生产过程中,由于磁盘空间.保留周期等因素,会对系统.应用等日志提出要求,要求系统日志定期进行轮转.压缩和删除,从而减少开销,而系统自带的logrotate  则是一个简单又实用的小工具,下面着 ...

  8. highcharts图表及报表展示、导出数据

    @ 目录 前言 一.使用highcharts前后端交互展示图表,及使用报表导出 二.实现思路 1.图表可以选择echarts.highcharts,我们这里选择highcharts(echarts使用 ...

  9. Calendar类介绍_获取对象的方式和Calendar类的常用成员方式

    java.util.Calendar是日历类,在Date后出现,替换掉了许多Date方法.该类将所有可能用到的时间信息封装为静态成员变量,方便获取.日历类就是方便获取各个时间属性的. Calendar ...

  10. Windows Embedded CE 6.0开发环境的搭建(2)

    最近开始在学习嵌入式,在这里首先得安装Windows Embedded CE 6.0,其中遇到了很多问题,电脑的系统以及相关配置都会在安装过程中受到影响,因此笔者就安装中的问题以及环境搭建来介绍一下. ...