Marcus
Marcus

Reputation: 5447

Which is better? Does it even matter?

This may be a silly question, but say I want to get two values from an OnSelectedIndexChanged event in my ASP .NET app.
Which is better?

var personId = Convert.ToInt32(((GridView)sender).SelectedDataKey.Values["PersonId"]);
var name = ((GridView)sender).SelectedDataKey.Values["Name"].ToString();

OR

var gView = (GridView)sender;
var personId = Convert.ToInt32(gView.SelectedDataKey.Values["PersonId"]);
var name = gView.SelectedDataKey.Values["Name"].ToString();

Does casting the GridView twice make that much of a difference as far as speed goes? What if I was pulling more values? Is there some other

Upvotes: 0

Views: 158

Answers (6)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

I'd go with little improved second option, because of one casting and readability

var key = ((GridView)sender).SelectedDataKey;
var personId = Convert.ToInt32(key.Values["PersonId"]);
var name = key.Values["Name"].ToString();

Also this code shows intent better - you are working with DataKey here, not with whole GridView, so you don't need to keep reference to GridView object.

Upvotes: 1

G.Y
G.Y

Reputation: 6159

Casting twice cost more than casting once.
There is an option that the compiler will output the same .dll in both cases meaning it already optimizing it for you - to be extra sure - complie it with the first choice and save the .DLL you get, afterwards compile it with the second choice.
Compare the size of the two .DLL's - if it is same - the complier already optimized it for you otherwise go for the 2nd choice as it is more readable and more optimized.

Upvotes: 0

Tim S.
Tim S.

Reputation: 56536

The latter (cast once) would be slightly faster. I also prefer its readability. The performance difference is so slight that to really consider it would most likely be a pointless micro-optimization in this case.

Upvotes: 5

Joaquim Rendeiro
Joaquim Rendeiro

Reputation: 1388

The compiler will optimize that for you. I'd prefer the second, for readability.

Upvotes: 3

moribvndvs
moribvndvs

Reputation: 42497

I would opt not to cast more than I needed to. It won't matter much performance-wise, in this case, but it's easier to follow.

Upvotes: 1

Stilgar
Stilgar

Reputation: 23551

Not casting is better. In theory it is faster in practice it doesn't matter. However the fact that you cast once results in clearner code.

Upvotes: 2

Related Questions