What is fastest: (int), Convert.ToInt32(x) or Int32.Parse(x)?

It depends on what you expect x to be

If x is a boxed int then (int)x is quickest.

If x is a string but is definitely a valid number then int.Parse(x) is best

If x is a string but it might not be valid then int.TryParse(x) is far quicker than a try-catch block.

The difference between Parse and TryParse is negligible in all but the very largest loops.

If you don’t know what x is (maybe a string or a boxed int) then Convert.ToInt32(x) is best.

These generalised rules are also true for all value types with static Parse and TryParse methods.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)