rob_carr_76748
Oct 02, 2018Nimbostratus
iRule/TCL data type coercion
I'm working through some F5 training material for developing irules, and on the subject of how to make your rules more efficent, the following slide about data type coercion is presented:
The notes attached to this slide say:
The "incr x" command forces a data type conversion of the variable "x" into an integer. While "x" is still stored as a string, it is also likely that the iRule interpreter still has an integer version of this by the time it gets to the comparison, which occurs on the very next line. In this case, a polymorphic comparison with "==" would be faster than converting 4 into a string.
Rule of thumb – use "eq" or "equals" when you know both operands are strings, because it is faster. Use "==" if you are not sure.
When you access a variable, you can coerce it into a given data type depending on the operation you’re using it with. This means that the same variable can be interpreted differently in a series of different operations.
In this example, x is an integer, because incr only works with integers and so the value of 4 is coerced into being an integer.
If two strings are "large" and can be converted into integers, it’s generally faster to convert and compare rather than compare as long strings.
I'm having trouble making sense of this.
Looking at the left-hand example, 'x' starts out as a string, is coerced to an integer by the incr command, then compared to '4' (which is a string, not an integer as the first paragraph of the slide notes implies) via the equals operator, which only works on strings, requiring 'x' to be coerced back to being a string. Two coercion operations.
Looking at the right-hand example, 'x' starts out as a string, is coerced into an integer by the incr command, then compared to the string '4' via the polymorphic '==' operator, which handles all types of comparisons, but 'x' is now an integer and '4' is a string, so one of them is going to have to be coerced, either 'x' to a string or '4' to an integer, which brings us again to two coercion operations.
Clearly I'm not understanding something here.