I tried some tests with the following code. This application is for rails. Rails v.5.1.1 / Ruby v2.4.1
Initially, the goal is simply to count the number of visits in any show actions of some controllers, for example:
include SessionCount ... def show ... @counter = increment_session_counter ...
Then I could display the counter in the respective views.
So I took care of the appropriate code from both versions of the default destination, which I wanted to check:
module SessionCount private
To test both versions of the default destination, I changed the code of my controllers as follows:
include SessionCount ... def show ... t0 = Time.now 1000000.times do session[:counter] = 0;
Note. In this code, initialization is here to provide a “happy journey” (where the value is not equal to zero). In a real scenario, this will happen only for the first time for a given user.
Here are the results:
I get an average of 3100 ms with version A operator ( ||= ).
I get an average of 2000 ms with version B ( rescue ).
But the interesting part begins now.
In the previous code, the code is executed after a “happy journey”, where an exception does not occur.
Therefore, I changed the initialization that I did for normalization purposes as follows to provide an “exception path”:
1000000.times do session[:counter] = nil;
And here are the results:
I get an average of 3500 ms with the operator version A ( ||= ).
I get an average of about 60,000 ms with version B ( rescue ). Yes, I tried a couple of times only.
So, I can conclude that spickermann said exception handling is really quite expensive.
But I think that there are many cases when the first initialization is very rare (for example, on a blog where there is no message at the very beginning).
In such situations, there is no reason to test nil every time, and it would be interesting to use exception handling.
I'm wrong?
I don’t want a bit about some ms .. Here I just want to know if this idiom has a design meaning. I see the difference in both versions, as the difference between while... end and do ... while , as the intention does not match.