subroutine perl with inline
Asked Answered
W

1

6

I have a Perl function, which does not return any value. It does not take any arguments also.

sub test {
    #do my logic
}

Can I do as :

sub test() {
    #do my logic
}

Will the subroutine test be inlined? Will this work? (meaning will the function call be replaced with the function definition. And will my program execute faster?)

The function test() is being called 5000 times. And my Perl program takes a longer time to execute than expected. So I want to make my program faster. Thanks in advance!

Wizardry answered 19/6, 2018 at 6:4 Comment(5)
Re "Will the subroutine test be inlined?", Only if #do my logic is a constant or a lexically-scoped var.Wakashan
@Wakashan That sounds like an answer and might stay the only one. Would you like to make it an answer which gets this out of the list of unanswered questions?Chickenhearted
If your program is slow, use a profiler. See Devel::NYTProf.Serranid
Even thinking about inlining implies that the function is small and simple. Is that the case? (If it isn't just forget about it, in any language.) Can you then show the function?Gentoo
i donot understand what is meant by - constant or a lexically-scoped var.Wizardry
G
6

This is answered in Constant Functions in perlsub

Functions with a prototype of () are potential candidates for inlining. If the result after optimization and constant folding is either a constant or a lexically-scoped scalar which has no other references, then it will be used in place of function calls made without &. Calls made using & are never inlined. (See constant.pm for an easy way to declare most constants.)

So your sub test() should be inlined if it satisfies the above conditions. Nobody can tell without seeing the function, so either show it or try.

This is most easily checked with B::Deparse, see further down the linked perlsub section.

I would urge you to profile the program to ensure that the function call overhead is the problem.

Gentoo answered 19/6, 2018 at 6:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.