Michael Culley said:
So what you're really saying is that they are resourse intensive
otherwise you wouldn't have added the "reasonably infrequently". This
function below is around 3000 times slower without the first line.
Only if you feed it DBNull all the time though, presumably... What
happens if you only feed it DBNull once in a million times, as might
reasonably the case in some applications? In that case, it could well
be *slower* to avoid the non-occurring exception in the common case
than the cost of the exception in the rare case.
Of course you shouldn't go out of your way to avoid exceptions
But there are times where it's possible to avoid it, but that *does*
involve going out of your way. On such occasions, I'd usually go with
the simpler code, unless I had any reason to believe it would be a
significant performance problem. For instance, I've shown elsewhere
that if you've got a lot of dodgy string data which is going to be
converted to ints, it's much faster to do a hard-coded check
beforehand. However, if I'm reasonably expecting the data to be
correct, I could avoid a *possible* exception by using that check, but
I wouldn't bother, because it would make the code more complicated for
very little (if any) performance gain.
but if it's reasonable to avoid them like in the code below
you may as well.
int ToInt32(object value)
{
if(value == DBNull.Value) return 0;
try
{
return Convert.ToInt32(value);
}
catch
{
return 0;
}
}
Yes, where possible it's worth avoiding them, but as much for stylistic
reasons as performance ones. If you end up getting to the situation
where you're throwing enough exceptions that it becomes a bottleneck in
your code, there's probably more wrong than just performance.
Damn you must have a *really* fast laptop. My p4 2.4 desktop couldn't get
anywhere near that.
It's a P4 3.06GHz.