Ada 95 Quality and Style Guide | Chapter 10 |
10.6.6 Constraint Checkingguideline
Use strong typing with carefully selected constraints to reduce run-time constraint checking when measured performance indicates. example
In this example, two potential constraint checks are eliminated. If the function Get_Response returns String, then the initialization of the variable Input would require constraint checking. If the variable Last is type Positive, then the assignment inside the loop would require constraint checking:
... subtype Name_Index is Positive range 1 .. 32; subtype Name is String (Name_Index); ... function Get_Response return Name is separate; ... begin ... Find_Last_Period: declare -- No Constraint Checking needed for initialization Input : constant Name := Get_Response; Last_Period : Name_Index := 1; begin -- Find_Last_Period for I in Input'Range loop if Input(I) = '.' then -- No Constraint Checking needed in this `tight' loop Last_Period := I; end if; end loop; ... end Find_Last_Period;rationale
Because run-time constraint checking is associated with slow performance, it is not intuitive that the addition of constrained subtypes could actually improve performance. However, the need for constraint checking appears in many places regardless of the use of constrained subtypes. Even assignments to variables that use the predefined subtypes may need constraint checks. By consistently using constrained subtypes, many of the unnecessary run-time checking can be eliminated. Instead, the checking is usually moved to less frequently executed code involved in system input. In the example, the function Get_Response may need to check the length of a user-supplied string and raise an exception.
Some compilers can do additional optimizations based on the information provided by constrained subtypes. For example, although an unconstrained array does not have a fixed size, it has a maximum size that can be determined from the range of its index. Performance can be improved by limiting this maximum size to a "reasonable" number. Refer to the discussion on unconstrained arrays found in NASA (1992).
< Previous Page | Search | Contents | Index | Next Page > |
1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 |
TOC | TOC | TOC | TOC | TOC | TOC | TOC | TOC | TOC | TOC | TOC |
Appendix | References | Bibliography |