Search code examples
initializationadaelaboration

Ada: Declaration & assignment overhead


I'm curious about the initialization within Ada procedures: Suppose I have the following procedure:

procedure Foo (Bar : Integer) is
    Another_Bar : Integer := Bar;
begin
    ...
end Foo;

Should the assignment to Another_Bar have the same overhead as

procedure Foo2 (Bar : Integer) is
    Another_Bar : Integer;
begin
    Another_Bar := Bar;
    ...
end Foo;

My question is essentially if both assignments generate the same assembly instructions and thus are equal in speed? (without detailing the target machine)


Solution

  • Based on the Ada language standard, there is no general reason why those two forms of code should have different performance. It would all depend on the target machine and the compiler being used. Depending on the rest of the code in the procedure, some compilers could even completely optimize away the Another_Bar variable.

    However, there is a semantic difference, which could be important if the subtypes of Bar and Another_Bar were different -- for example, if Another_Bar were declared as Positive instead of Integer. Namely, in the first form any exception raised by the initialization of Another_Bar (say, because Bar has a negative value) is not handled by the possible exception handlers in the procedure itself, but is propagated to the caller. In the second form, where Another_Bar is assigned after the begin, exceptions from that assignment can be handled by the procedure's own exception handlers.