Home > Net >  Perl optimization: inlining a function changed the results
Perl optimization: inlining a function changed the results

Time:09-17

I profiled some code, and there is one function which stood out and I was wondering if there is a way to optimize it:

The function is defined as:

sub convert_arrayref {
   if(ref($_[0]) eq 'ARRAY') {
       return join(($_[1] || ","), @{$_[0]});
   }
   else {
     return $_[0];
   }
}

Most of the times the else block will get executed, and I was wondering if I could inline it rather than making a function call. The calling code looks as follows:

$data = convert_arrayref($data, '&')

So, what I did was change the calling code as:

if ($data eq 'ARRAY') {
    $data = join('&', $data)
}

I thought this would be equivalent. However, the results are different. I am wondering if I have done something wrong here.

CodePudding user response:

You get different results because you did not replicate the functionality of the if clause. You need to use ref to check if your variable is an array reference, and you need to deference the variable:

if (ref($data) eq 'ARRAY') {
    $data = join('&', @{ $data })
}
  •  Tags:  
  • perl
  • Related