When you have a cast you should avoid asking the compiler to figure out what kind of data should be returned. This is more about objects and the string data type.
For example I've seen (and to be honest I myself did the following mistake when getting data from DataSet. Don't laugh in .NET 1.1 and 2.0 there was no Linq :)
foreach (DataRow row in dsReportSource.Tables[0].Rows)
{
string strName = row["name"].ToString();
}
The compiler will let you think that it knows how to do the fastest transformation from object (in the dataset all the columns in a row are objects) to the destination type (in our case - string). But it will only let you think so. What will actually happen is that the compiler will slow down the data acquisition due to some internal checks and conversions ...
Instead do the following (as you are more than sure that this column is string):
foreach (DataRow row in dsReportSource.Tables[0].Rows)
{
string strName = (string)row["name"];
}
This way you tell the compiler - "Look, don't even bother to try to infer the type for me. I am telling you this is a string, so please just treat it as string). And it makes sense - after you have a column of type NVARCHAR in the database it will always come to you as a string (masked as object :).
Now there are even worse cases like:
foreach (DataRow row in dsReportSource.Tables[0].Rows)
{
int iId = int.Parse(row["id"].ToString());
}
As you can see you are parsing the id column. You know it's int. But int.Parse can only work on strings, so you are required to turn this object to string, calling its .ToString() method. This will slow down your code insignifficantly on few rows and signifficantly on more rows (few thousands for example).
The following is also wrong:
foreach (DataRow row in dsReportSource.Tables[0].Rows)
{
int iId = Convert.ToInt32(row["id"]);
}
Here you are telling your compiller that you are sure the parameter (row["id"]) will cast to Int32 without problems.
But here you are telling your compiller only 50% of the truth. After you KNOW it is int, just be honest and say:
foreach (DataRow row in dsReportSource.Tables[0].Rows)
{
int iId = (int)row["id"];
}
This applies not only to DataSets but everywhere you have a fixed datatype and you know what the type is.
Don't let your compiler do the work.
Just look at your project and try to find places where you are uncertain about fixed datatype.
Change it to be a direct cast and I am pretty sure you will experience speed improvements.
No comments:
Post a Comment