Int32.TryParse()或(INT?)command.ExecuteScalar()TryParse、INT、ExecuteScalar、command

2023-09-03 00:45:23 作者:回不去的过去

我有一个SQL查询,它返回只有一个字段 - 类型为int的ID

和我不得不使用它在C#code整数。

哪种方式速度更快,占用内存更少?

 内部ID;
如果(Int32.TryParse(command.ExecuteScalar()。toString()方法,掉id))
{
  //使用ID
}
 

 诠释? ID =(INT?)command.ExecuteScalar();
如果(id.HasValue)
{
  //使用id.Value
}
 
C String转int主要有四种方法

 诠释? ID = command.ExecuteScalar()以int ?;
如果(id.HasValue)
{
  //使用id.Value
}
 

解决方案

这三个性能之间的差异聪明的可以忽略不计。瓶颈是从数据库中的数据转移到你的应用程序,而不是一个简单的铸件或方法调用。

我会跟去:

 诠释? ID =(INT?)command.ExecuteScalar();
如果(id.HasValue)
{
  //使用id.Value
}
 

据早期失败,如果有一天人们改变命令返回一个字符串或日期,至少它会崩溃,你将不得不解决它的机会。

我也只是去用一个简单的 INT 铸造如果我一直期待的命令返回一个结果。

请注意,我一般是preFER返回一个出参数比做执行标,执行标感到脆弱(第一行中的第一列是一个返回值不坐适合我的约定)。

I have a SQL query which returns only one field - an ID of type INT.

And I have to use it as integer in C# code.

Which way is faster and uses less memory?

int id;
if(Int32.TryParse(command.ExecuteScalar().ToString(), out id))
{
  // use id
}

or

int? id = (int?)command.ExecuteScalar();
if(id.HasValue)
{
  // use id.Value
}

or

int? id = command.ExecuteScalar() as int?;
if(id.HasValue)
{
  // use id.Value
}

解决方案

The difference between the three performance wise is negligible. The bottleneck is moving the data from the DB to your app, not a trivial cast or method call.

I would go with:

int? id = (int?)command.ExecuteScalar();
if(id.HasValue)
{
  // use id.Value
}

It fails earlier, if one day people change the command to return a string or a date, at least it will crash and you will have a chance to fix it.

I would also just go with a simple int cast IF I always expected the command to return a single result.

Note, I usually prefer returning an out param than doing the execute scalar, execute scalar feels fragile (the convention that the first column in the first row is a return value does not sit right for me).