-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Generate direct string lengths and unit-step slices #7058
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
Draft
Alek99
wants to merge
1
commit into
main
Choose a base branch
from
codex/perf-direct-string-operations
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Draft
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
1 change: 1 addition & 0 deletions
1
packages/reflex-base/news/+direct-string-operations.performance.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| Avoid splitting entire strings into arrays when computing string Var lengths or slices with an omitted or unit step. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,24 @@ | ||
| """Benchmarks for generating string Var operations.""" | ||
|
|
||
| import pytest | ||
| from pytest_codspeed import BenchmarkFixture | ||
| from reflex_base.vars.base import Var | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("operation", ["length", "slice", "unit_slice"]) | ||
| def test_string_operation_codegen(operation: str, benchmark: BenchmarkFixture) -> None: | ||
| """Measure Python expression generation, excluding JavaScript execution. | ||
|
|
||
| Args: | ||
| operation: The string operation to generate. | ||
| benchmark: The CodSpeed benchmark fixture. | ||
| """ | ||
| value = Var(_js_expr="state.text").to(str) | ||
| start = Var(_js_expr="state.start").to(int) | ||
| stop = Var(_js_expr="state.stop").to(int) | ||
| operations = { | ||
| "length": value.length, | ||
| "slice": lambda: value[start:stop], | ||
| "unit_slice": lambda: value[start:stop:1], | ||
| } | ||
| benchmark(lambda: str(operations[operation]())) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,81 @@ | ||
| """String operation code generation and JavaScript semantics.""" | ||
|
|
||
| import json | ||
| import shutil | ||
| import subprocess | ||
|
|
||
| import pytest | ||
| from pytest_mock import MockerFixture | ||
| from reflex_base.utils.imports import ImportVar | ||
| from reflex_base.vars.base import Var, VarData | ||
| from reflex_base.vars.sequence import ArraySliceOperation | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("step", [None, 1]) | ||
| def test_string_slice_preserves_metadata(step: int | None) -> None: | ||
| """Direct slices retain source and dynamic-bound imports and hooks.""" | ||
| source_data = VarData(imports={"source": [ImportVar(tag="text")]}) | ||
| start_data = VarData(hooks={"const start = useStart()": None}) | ||
| stop_data = VarData(imports={"bounds": [ImportVar(tag="stop")]}) | ||
| source = Var(_js_expr="text", _var_data=source_data).to(str) | ||
| start = Var(_js_expr="start", _var_data=start_data).to(int) | ||
| stop = Var(_js_expr="stop", _var_data=stop_data).to(int) | ||
|
|
||
| result = source[start:stop:step] | ||
|
|
||
| assert str(result) == "text.slice(start, stop)" | ||
| assert result._var_type is str | ||
| assert result._get_all_var_data() == VarData.merge( | ||
| source_data, start_data, stop_data | ||
| ) | ||
| assert str(source.length()) == "text.length" | ||
| assert source.length()._var_type is int | ||
| assert source.length()._get_all_var_data() == source_data | ||
|
|
||
|
|
||
| @pytest.mark.parametrize("step", [2, -1, -2, 0, Var(_js_expr="step").to(int)]) | ||
| def test_string_slice_other_steps_keep_array_path( | ||
| step: int | Var, mocker: MockerFixture | ||
| ) -> None: | ||
| """Non-unit and dynamic steps still delegate to the existing array slicer.""" | ||
| source = Var(_js_expr="text").to(str) | ||
| array_slice = mocker.patch.object( | ||
| ArraySliceOperation, "create", return_value=Var(_js_expr="sliced").to(list[str]) | ||
| ) | ||
| index = slice(1, 8, step) | ||
|
|
||
| source[index] | ||
|
|
||
| array_slice.assert_called_once() | ||
| assert str(array_slice.call_args.args[0]) == 'text.split("")' | ||
| assert array_slice.call_args.args[1] is index | ||
|
|
||
|
|
||
| def test_string_length_and_slices_preserve_utf16() -> None: | ||
| """Generated operations preserve code-unit semantics in JavaScript.""" | ||
| node = shutil.which("node") | ||
| if node is None: | ||
| pytest.skip("Node.js is required to execute generated string operations") | ||
| source = Var(_js_expr="text").to(str) | ||
| start = Var(_js_expr="start").to(int) | ||
| stop = Var(_js_expr="stop").to(int) | ||
| expressions = [str(source[start:stop]), str(source[start:stop:1])] | ||
| values = ["", "abc", "😎abc\ud800", "a\u0301bc", "\0\n\r"] | ||
| script = f"""const strings = {json.dumps(values)}; | ||
| const slices = {json.dumps(expressions)}.map( | ||
| expression => new Function("text", "start", "stop", `return ${{expression}}`) | ||
| ); | ||
| const length = new Function("text", {json.dumps(f"return {source.length()!s}")}); | ||
| for (const text of strings) {{ | ||
| if (length(text) !== text.split("").length) throw Error("length mismatch"); | ||
| for (const start of [undefined, -100, -3, 0, 1, 2, 100]) {{ | ||
| for (const stop of [undefined, -100, -3, 0, 1, 2, 100]) {{ | ||
| const expected = text.split("").slice(start, stop).join(""); | ||
| for (const slice of slices) {{ | ||
| if (slice(text, start, stop) !== expected) throw Error("slice mismatch"); | ||
| }} | ||
| }} | ||
| }} | ||
| }} | ||
| """ | ||
| subprocess.run([node, "-e", script], check=True, capture_output=True, text=True) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
A unit step represented as a constant
LiteralNumberVar, such asLiteralNumberVar.create(1), is supported by the existing slice machinery but fails theisinstance(i.step, int)check. It therefore still generates the allocation-heavysplit("").slice(...).join("")path, leaving the intended constant-unit-step optimization incomplete. Recognize integer literal Vars whose value is1and add a regression case alongside the Pythonintcase.