DedalusProject / dedalus

A flexible framework for solving PDEs with modern spectral methods.
http://dedalus-project.org/
GNU General Public License v3.0
513 stars 121 forks source link

Optimize parsing for improved performance #240

Closed GuilhermeMonteiroPeixoto closed 1 year ago

GuilhermeMonteiroPeixoto commented 1 year ago

Optimize equation parsing functions for improved performance

  1. Use re.compile to pre-compile regular expressions, instead of calling re.match repeatedly.

  2. Use str.partition instead of str.find and slicing to split a string at the first occurrence of a separator. This can be faster for short strings.

  3. Use str.strip to remove leading and trailing whitespace, instead of slicing.

  4. Use str.count to count the occurrences of a character in a string, instead of iterating over the string and incrementing a counter.

  5. Use tuple unpacking to assign variables to single-element tuples, instead of indexing.

  6. Avoid unnecessary string concatenation by using str.format to interpolate variables into a string.

kburns commented 1 year ago

Thanks for the contribution but it looks like the regular expression doesn't quite work since it matches/splits of the first equals sign, which isn't necessarily top level (e.g. as in the docstring example). These items are far from being performance critical for Dedalus and the current implementation isn't causing any issues, so I'm going to close the PR for now but would be happy to reconsider if the regex is fixed.