Differences between Parse() vs Tryparse()

Asked

Viewed 10,591 times

59

  • There is a difference in performance between the two?
  • In which situations apply?
  • Which is the most recommended to be used?

6 answers

42


What methods are you talking about? There are, on the date I am writing this answer, 1383 methods Parse() and 266 TryParse() only in the . NET source code provided by Microsoft (Behold also on Github). Of course this includes all overloads.

Parse whole

I imagine they’re the methods used to convert a string which probably contains numerical digits in numerical values of a certain type. Although there are different implementations, they are similar and I will focus on int.Parse and the int.TryParse.

Ways to use:

int value;
try {
    value = int.Parse("!123x6");
} catch(FormatException) {
    value = -1; //solução horrível mas serve para o exemplo
}

and

int value;
if (!int.TryParse("!123x6", out value)) {
    value = -1; //solução horrível mas serve para o exemplo
}

The second form seems cleaner to me. And in C# 7 can still be shorter:

if (!int.TryParse("!123x6", out var value)) {
    value = -1;
}

I put in the Github for future reference.

Performance

You have already been shown the time comparison. But this is not so important. Remember that premature optimization should not be done. Only worry if there are metrics that indicate that one of these methods is causing a harmful slowness. But by coincidence the fastest is the most indicated, semantically speaking.

Invalid Data Exception X

You use one of these methods to convert a text into a number, if and only if there is a valid number identifiable by the parse. If it is not possible to convert, this is a invalid data? Or is a exception in the implementation of the programme?

The answer you give will determine which of the methods to use. Have to use what is semantically suitable before any other reason, especially optimization.

I understand and know several experienced programmers who understand that in the vast majority of cases, the fact that the conversion is not possible indicates the invalidity of the analyzed text for the required purpose and a data invalidity should be notified to the program in a simple way. This is information that is part of the "business rule" and not the conversion mechanism. Actually I can’t see a case to use the Parse that is not fixing the wrong mechanism. The TryParse() was created later because it was identified that the Parse() was the wrong mechanism.

Exception degrades performance

To excellent response from the OS clearly shows that the performance of Parse() can only be comparable, but not better, if all the analyzed data are valid. The more invalid data in your roll, worse gets the performance of Parse(). Because handling exceptions is an extremely slow process.

You can say that there are several exceptions that can be thrown during the process and you might want to know which exception it is. But for what? What will you do with this information? If the data is invalid, you will receive an exception FormatException. What this helps more than one true or false? If it is another exception, it indicates a programming error and not the invalidity of the data. How will you fix a programming error? A try-catch does not solve programming problems. If anyone still thinks they can handle it, please stop doing this. A programming problem should only be manipulated before exiting the application, probably by making a log and perhaps improving the presentation of the error to the end user, if the error arrived in production. Can not do anything more!

Exception is not normal flow

Okay, for everything there is an exception (in the broad sense of the word, not the technical programming feature), so there may be a case that you can handle, but it’s rare. Usually when you find a way to deal with a programming error, you probably shouldn’t be dealing with exception (in the sense of Exception), should have a way to intercept it through the program flow. Exception treatment is not normal flow. Exception treatment should be done with something unexpected. Invalid data is expected, is something that is normal to happen and needs to be handled appropriately.

It is necessary to better understand how to use exceptions. I deal with this subject in other answers here and here and more broadly here (a good place to start browsing for several other answers on the subject).

Why use the Parse()?

I can’t imagine using the Parse() for nothing. But I will have no problem using it when I realize that it will help some specific case. Maybe a case that needs to solve a corner case, one bug of the . NET, I don’t know, but under normal conditions, there’s no reason to use it.

If you want to try to understand the methods better, read their sources (you have to navigate through the calls to see all the paths, but the site UI helps): Parse() and TryParse().

As a last note, just don’t use the TryParse() as in that question. The return is untreated. If a given is wrong, you have an invisible logic error in your program. Of course I don’t know if there are guarantees that the TryParse() never give invalid data with the data set treated there. But I wouldn’t trust any guarantees. Computers fail, humans fail even more. In this case a Parse() would have been better because it would at least give a programming error and break the application. Not ideal but better than accepting invalid data (well, there’s a case for the Parse(), you’re sure you’ll never fail).

20

Parse makes an exception if he cannot analyze the value, whereas TryParse returns a value boolean indicating whether he succeeded.

TryParse not only is a try/catch internally - the main point is that it is implemented without exceptions so that it is fast. In fact, the way it is most likely is that the method is implemented internally Parse will call TryParse and then throws an exception if it returns false.

In a nutshell, use Parse, if you are sure that the value will be valid. Otherwise, use TryParse.

If the string cannot be converted to a whole, then:

  • int.Parse() will throw an exception.
  • int.TryParse() will return false (but will not make an exception).

Source

16

The Parse spear a exception if he can’t convert the value, the Tryparse returns a bool indicating whether or not he succeeded.

Example:

int n = int.Parse(textBoxNumero.Text);

For the above code, imagine that the textBoxNumber receive 5. The parse will be done and n will be 5. Now, if the textBoxNumber receive abc it will generate an exception, which should be treated with Try-catch.

int n = 0;
bool teste = int.TryParse(textBoxNumero.Text, out n);

For the above code, imagine that the textBoxNumber receive 5. The parse will be done and n will be 5 and test will be true. Now, if the textBoxNumber receive abc, n will keep the initialized value 0 and test will be false because he couldn’t perform Parse.

About performance, the ideal is: use Parse, if you are sure that the value can be converted in the way you want, because it is faster; otherwise you need to check if the conversion will be possible, use Tryparse.

  • 1

    Why the Parse would perform better?

  • While Parse only does the information conversion, Tryparse checks to see if it is possible to convert and then do the conversion. Tryparse is nothing more than a function that checks if it is possible to perform the conversion and after that invokes Parse.

  • 2

    See the other answers and links to the OS. The evidence indicates that the TryParse better.

13

The difference, basically, is that Parse makes an exception, while TryParse nay.

As regards the performance, TryParse is faster than Parse because it does not use try/catch. But depending on how often your program performs this type of interpretation per second, it may not make the slightest difference in the overall performance of your program (in this link there is a small benchmark comparing the two).


There is also a clear difference in the way functions are used:

string str = "100a0";
int numero;

// algo do tipo
int resultado = int.TryParse(str, out numero) ? numero : 0;

Against:

try
{
    int numero = Int32.Parse(str);
}
catch (Exception e)
{
    Console.WriteLine("Parse Falhou");
}

Now saying which is best is a bit tricky. An advantage of Parse is that you (by way of exception) can know what was the type of error that occurred during execution. But, it all depends on the context.

11

Freely translated of this Stack Overflow question:

Parse fires an exception if you cannot convert the value while TryParse returns a bool indicating whether it was successful.

TryParse doesn’t just make a try / catch internally - the idea is that it be implemented without exceptions to be fast. In fact, the most likely way to be implemented is with the method Parse trying to execute TryParse and fire an exception if you return false.

In short, use Parse if you are sure the value will be valid; otherwise, use TryParse.

8

I’ve read all the answers, but none specifically talks about their performance.

There is an answer back in the OS with a time comparison table.

There is also a post on the MSDN blog talking about it, but unfortunately the photos didn’t open here at home.

As a personal experience, I might add that TryParse was always faster than the Parse, as well as the as works a little faster than a type cast conventional.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.