Skip to content

Commit

Permalink
[jsinterp] Add short-cut evaluation for common expression
Browse files Browse the repository at this point in the history
* special handling for (d%e.length+e.length)%e.length speeds up ~6%
  • Loading branch information
dirkf committed May 11, 2023
1 parent a85a875 commit 6ed3433
Showing 1 changed file with 20 additions and 2 deletions.
22 changes: 20 additions & 2 deletions youtube_dl/jsinterp.py
Original file line number Diff line number Diff line change
Expand Up @@ -502,8 +502,15 @@ def interpret_statement(self, stmt, local_vars, allow_recursion=100):
expr = self._dump(inner, local_vars) + outer

if expr.startswith('('):
inner, outer = self._separate_at_paren(expr)
inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)

m = re.match(r'\((?P<d>[a-z])%(?P<e>[a-z])\.length\+(?P=e)\.length\)%(?P=e)\.length', expr)
if m:
# short-cut eval of frequently used `(d%e.length+e.length)%e.length`, worth ~6% on `pytest -k test_nsig`
outer = None
inner, should_abort = self._offset_e_by_d(m.group('d'), m.group('e'), local_vars)
else:
inner, outer = self._separate_at_paren(expr)
inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
if not outer or should_abort:
return inner, should_abort or should_return
else:
Expand Down Expand Up @@ -957,6 +964,17 @@ def extract_object(self, objname):

return obj

@staticmethod
def _offset_e_by_d(d, e, local_vars):
""" Short-cut eval: (d%e.length+e.length)%e.length """
try:
d = local_vars[d]
e = local_vars[e]
e = len(e)
return _js_mod(_js_mod(d, e) + e, e), False
except Exception:
return None, True

def extract_function_code(self, funcname):
""" @returns argnames, code """
func_m = re.search(
Expand Down

0 comments on commit 6ed3433

Please sign in to comment.