Which of IsDBNull and IsNull should be used?

CJ7 picture CJ7 · Jul 9, 2013 · Viewed 22.8k times · Source

If in VB.NET I have DataRow and I want to test whether a column value is Null, should I use:

myDataRow.IsNull("Column1")

OR

IsDBNull(myDataRow("Column1"))

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Jul 27, 2013

Short answer: use the first way, it is faster, because the first method uses a pre-computed result, while the second method needs to recompute it on the fly every time you call it.

Long answer: (you need to read C# code to understand this part; MS supplies framework code in C#, but VB programmers should be able to get the general idea of what's going on)

Here is what happens inside the IsNull call of DataRow:

public bool IsNull(string columnName) {
    DataColumn column = GetDataColumn(columnName);
    int record = GetDefaultRecord();
    return column.IsNull(record);
}

The column.IsNull performs a quick assertion, and forwards the call to DataStorage, an internal class:

internal bool IsNull(int record) {
    Debug.Assert(null != _storage, "no storage");
    return _storage.IsNull(record);
}

Finally, here is what _storage.IsNull does:

public virtual bool IsNull(int recordNo) {
    return this.dbNullBits.Get(recordNo);
}

Since dbNullBits is a BitArray, this operation completes very quickly.

Now consider what the indexer myDataRow("Column1") does (you call this indexer before passing its result to IsDBNull):

get {
    DataColumn column = GetDataColumn(columnName);
    int record = GetDefaultRecord();
    _table.recordManager.VerifyRecord(record, this);
    VerifyValueFromStorage(column, DataRowVersion.Default, column[record]);
    return column[record];
}

Note that the first two lines of IsNull method and the indexer are identical. However, the three rows that follow need to perform validation, and fetch the value itself. Only after that your code can start computing its target value - a flag that tells it if the value is DBNull or not. This requires more computation, but more importantly, it requires some computation every time you perform the check. This is slower than using a pre-computed value.