Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most Efficient Way to Test Object Type

Tags:

I have values stored as strings in a DataTable where each value could really represent an int, double, or string (they were all converted to strings during an import process from an external data source). I need to test and see what type each value really is.

What is more efficient for the application (or is there no practical difference)?

  1. Try to convert to int (and then double). If conversion works, the return true. If an exception is thrown, return false.
  2. Regular expressions designed to match the pattern of an int or double
  3. Some other method?
like image 395
Yaakov Ellis Avatar asked Aug 05 '08 07:08

Yaakov Ellis


People also ask

What method is used to determine the type of an object?

The GetType method is inherited by all types that derive from Object. This means that, in addition to using your own language's comparison keyword, you can use the GetType method to determine the type of a particular object, as the following example shows.

How do you check if a value is a type?

Use the typeof operator to check the type of a variable in TypeScript, e.g. if (typeof myVar === 'string') {} . The typeof operator returns a string that indicates the type of the value and can be used as a type guard in TypeScript.


2 Answers

Would use double.TryParse, it has performance benefits.

like image 70
gil Avatar answered Oct 31 '22 01:10

gil


I would say, don't worry so much about such micro performance. It is much better to just get something to work, and then make it as clear and concise and easy to read as possible. The worst thing you can do is sacrifice readability for an insignificant amount of performance.

In the end, the best way to deal with performance issues is to save them for when you have data that indicates there is an actual performance problem... otherwise you will spend a lot of time micro-optimizing and actually cause higher maintenance costs for later on.

If you find this parsing situation is really the bottleneck in your application, THEN is the time to try and figure out what the fastest way to solve the problem is. I think Jeff (and many others) have blogged about this sort of thing a lot.

like image 32
Mike Stone Avatar answered Oct 31 '22 01:10

Mike Stone