Direct cast or cast functions. What is the best option?

Asked

Viewed 230 times

4

In PHP, I realize that it is possible to do some things in countless ways.

One of them that comes to my attention is the functions and functionalities related to the conversion of types. It is possible to use both the type keyword and functions.

For example:

 $var = '1';

 var_dump((int) $var); // int(1)

 var_dump(intval($var)); // int(1);


 var_dump(strval($var)); // string(1)

 var_dump((string) $var); // string(1);

Given that function calls often consume more resources than using a language constructor or cast, would like to know:

  • What is the need to have these two functionalities?

  • For a cast of string for int, for example, which would be recommended? Use (int) or the intval?

  • Given that function calls often consume more resources than the call of a constructor, there is some situation that will actually need to use type conversion functions, rather than cast?

  • If it is specifically about Select a string in an int maybe this reply help. How much the last question depends on the rigor required by the code.

  • From what I read the recommendations are to use (int), one of the reasons being that intval() is not so fast, be direct cast is better. intval may, however, be based on a second argument. Sources: https://wiki.phpbb.com/Best_Practices:PHP and http://stackoverflow.com/questions/5339590/when-should-one-use-intval-and-when-int

  • @Miguel is already a beginning. In the specific case of intval has a second parameter. But we must remember that it is just an example I used. In this case the question fits in the sense of : "Cast vs Function"

2 answers

5


Given that function calls often consume more resources than using a language constructor or cast operator

This is false, at least conceptually speaking. A language construct can be quite complex. The only thing different in language construction is that the compiler has direct science to it.

In general an operator of cast or just tell the compiler that you know what you’re doing, in which case it’s clear that you’re faster than the function, or do a conversion operation that’s essentially the same as calling the function. Ok, it may be that the call is slightly worse. But it may be the opposite, you have to see the actual implementation of each one. It may be that the cast do more or be done wrong.

Differences

Of course there are situations where the function may be better or the only option. A second parameter indicating base conversion has already been mentioned.

A cast cannot convert anything to string adequately. The function strval() may be more successful, after all she tries to consult the method __toString() to make the conversion. The cast doesn’t do that.

Obviously some contexts only accept functions. This occurs in functions that are expected to send a string with a function name to do callback (horrible thing to do).

Some people find the function more readable than the cast. Not I.

Apparently the implicit type coercion is made with casting.

Performance

From everything I read it seems cast in PHP is always faster, at least slightly. So in theory it should be used preferably. A test I found was in the O.R.. Other well-completed test.

I did a similar test in some environments and got close to 50% differences for better in cast using PHP 7 and passing 200% in PHP 5.x.

The test was done with an algorithm that makes a conversion of string for int, it would not make sense to take a whole to convert to itself. I sent run millions of times to measure the operation and not the preparation.

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference. Obviously these environments are shared and their results are unreliable, do in your environment with the machine without running anything that disturbs.

I saw the test results of Daniel Omine. I did not see how it was done and results in 5.6. I saw that the result was 100 to 200 times slower than mine. Because there measures more the interpretation of the code than the operation itself.

That’s what I always say, in many cases PHP will have significant expense with the load and interpretation of the code and not so much with its execution itself. That’s why performance in PHP is not so important, after all the engine is already very slow. In this example the preparation consumed at least 99% of the time.

Rebound I’m speculating a little bit about the other test since it doesn’t show how it was done. So there may be a mistake about this.

Take your own test in the circumstances you will be using and keep an eye on the changes in each version. What is worth today may not be worth tomorrow.

These tests indicate to me that the function is poorly done and the cast should be preferred, especially in PHP 5 where the difference is brutal.

Completion

It’s what I’ve been able to find in the community, which I don’t consider the most reliable. That may be so, but there may be something that no one has noticed. I will not delve into the sources of language to find out, I will trust. Doesn’t seem to make a fundamental difference.

  • The part you quoted from the callbacks I imagined. One uses a intval and related with array_map('intval', ['1', '2']) for example. You find this horrible also was expected :p +1

  • @At least now you have a better solution. So I ask you, did they create a version of the function, or did they modify it to accept an anonymous function as an argument? Or still have to use it? The solution would not be grade 10, but it is possible and the fact that the possibility exists is a beautiful leap in quality.

  • 1

    array_map accepted Closure (anonymous function) as argument yes. The problem of passing functions like string is that it is very limited (passing parameters). Anyway, I am preferring to use Closure.

2

Testing with casting

Summary: 40531158 * 106 (4 millionths)

//
/*
O tempo tem uma variação
0.0000028610229
0.0000038146973
Normalmente entre 0.0000040531158 e 0.0000050067902
*/
$v = 42;
echo (int)$v;

Testing with the function

Summary: 59604645 * 106 (5.9 millionths)

//
/*
O tempo tem uma variação
0.0000109672546 (quando tem uma pausa de mais de 10 segundos entre uma execução e outra)

Normalmente entre 0.0000059604645 e 0.0000069604645
*/
$v = 42;
echo intval($v);

Observing:

After testing several times, both presented the same running time of 5.9 millionths for some time.

Ambience:

Macbook Pro 2011 (early)
CPU: Intel Core i7 2.2GHz
RAM: 4GB 1333 MHz DDR3

PHP: 7.0.10 (php-osx.liip.ch by Liip)
OS: El Capitan 10.11.6

*Testing with PHP 5.5.36, under the same environment, the results are identical.

Browser other questions tagged

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