Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

range/3 efficiency #1722

Closed
fadado opened this issue Sep 22, 2018 · 1 comment
Closed

range/3 efficiency #1722

fadado opened this issue Sep 22, 2018 · 1 comment

Comments

@fadado
Copy link

fadado commented Sep 22, 2018

As defined in builtin.jq I find range/3 hard to understand and slow due the double test:

def range($init; $upto; $by):
    def _range:
        if ($by > 0 and . < $upto) or ($by < 0 and . > $upto) 
        then ., ((.+$by)|_range)
        else . end;
    if $by == 0 then $init else $init|_range end 
    | select(($by > 0 and . < $upto) or ($by < 0 and . > $upto))
;

I suggest this alternative implementation:

def range($init; $upto; $by):
    label $out
    | ($by>0) as $inc
    | ($by<0) as $dec
    | $init|recurse(.+$by)
    | if $inc and . < $upto or $dec and . > $upto # in range?
      then .
      else break$out
      end
;

In my tests it is 1/3 faster!

@itchyny
Copy link
Contributor

itchyny commented Jun 25, 2023

The range/3 implementation has been improved by #1845 (fc6df0f).

@itchyny itchyny closed this as completed Jun 25, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants