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

use StringBuilder instead of Buffer in builtin and json package #550

Open
wants to merge 4 commits into
base: main
Choose a base branch
from

Conversation

hackwaly
Copy link
Contributor

@hackwaly hackwaly commented Jun 13, 2024

This PR introduce StringBuilder in builtin package. Thus avoid expensive Buffer operations when use Show trait in js/wasm-gc target.

Copy link
Contributor

coderabbitai bot commented Jun 13, 2024

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

builtin/builtin.mbti Outdated Show resolved Hide resolved
@coveralls
Copy link
Collaborator

coveralls commented Sep 24, 2024

Pull Request Test Coverage Report for Build 3332

Details

  • 25 of 31 (80.65%) changed or added relevant lines in 10 files are covered.
  • No unchanged relevant lines lost coverage.
  • Overall coverage decreased (-0.08%) to 83.201%

Changes Missing Coverage Covered Lines Changed/Added Lines %
builtin/assert.mbt 0 1 0.0%
builtin/autoloc.mbt 0 1 0.0%
builtin/string.mbt 2 6 33.33%
Totals Coverage Status
Change from base Build 3330: -0.08%
Covered Lines: 4096
Relevant Lines: 4923

💛 - Coveralls

@hackwaly hackwaly changed the title add StringBuilder use StringBuilder instead of Buffer in builtin package Sep 24, 2024
@hackwaly hackwaly marked this pull request as ready for review September 24, 2024 17:06
"array_nonjs_test.mbt": ["not", "js"]
"array_nonjs_test.mbt": ["not", "js"],
"stringbuilder_buffer.mbt": ["not", ["js"]],
"stringbuilder_concat.mbt": ["js"]
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mark todo: add wasm-gc here once we have support for jsstring proposal on wasm-gc

Copy link
Contributor

@bobzhang bobzhang left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we have some concrete data points to justify the change?

@Yoorkin
Copy link
Collaborator

Yoorkin commented Sep 25, 2024

I was supposed the StringBuilder is a faster (in js backend) and safer abstraction than Buffer. The Byte/Buffer is more suitable to writing binary stuff, programmers use it at their own risk: the Buffer::to_string do not check the output string. While StringBuilder will ensure the result is valid, and the String and Char being writing into are also already checked.

But in this PR StringBuilder::sub_string will write unpaired surrogate into result string, which is not valid in UTF16. Furthermore the StringBuilder is specialized for js backend and in others backends it just a wrapper of Buffer. It seems possible to do the same thing for Buffer's implementation, which leads the StringBuilder becoming a subset of Buffer.

I wonder why we still want to introduce a new abstraction. What functionalities should StringBuilder and Buffer provide separately?

@hackwaly
Copy link
Contributor Author

write_sub_string will be removed in StringBuilder. For now, to keep it just to make the diff smaller.

I wonder why we still want to introduce a new abstraction. What functionalities should StringBuilder and Buffer provide separately?

As you said, Buffer is more suitable to writing binary stuff, and StringBuilder only cares string concatenation. Buffer is not always the best approach to concat strings on each targets. It's too slow compared to concat based approach on js platform even wasm-gc platform if we support JsStringBuiltins proposal.

I'll present some data result later to show that.

@hackwaly
Copy link
Contributor Author

hackwaly commented Sep 25, 2024

The test result use this code: https://gist.github.com/hackwaly/24c2c16e25ef660772f3b06625ddb7a4

On my machine. Under js target: buffer based cost 5.7s. concat based cost 1.25s. @bobzhang

This PR also reduces simple println code javascript output by 120 SLOC.

@hackwaly hackwaly changed the title use StringBuilder instead of Buffer in builtin package use StringBuilder instead of Buffer in builtin and json package Sep 25, 2024
@Yoorkin
Copy link
Collaborator

Yoorkin commented Sep 25, 2024

and the String and Char being writing into are also already checked.

I was wrong because the invalid UTF16 string (contains unpaired surrogate) can still produced by String::sub_string, or just take a char by String::op_get and write it into StringBuilder. Will StringBuilder validate the input and result string in future?

@hackwaly
Copy link
Contributor Author

Probably not. It will align with the javascript's behavior. I think validation should be opt-in for users. It's best placed in unicode package?

Copy link

peter-jerry-ye-code-review bot commented Sep 25, 2024

From the provided git diff output, several changes have been made to update code to use a StringBuilder instead of a Buffer in various parts of the codebase. Here are the key observations and potential issues:

  1. Renaming and Consolidation:

    • The introduction of StringBuilder as a replacement for Buffer in many contexts suggests a desire to consolidate string-building operations under a more semantically appropriate name. This is generally a good practice as it improves readability and maintainability.
    • The split into stringbuilder_buffer.mbt and stringbuilder_concat.mbt based on the target environment (js or non-js) indicates a need for different implementations of string concatenation in different runtime environments. This could be due to performance considerations or specific native support for string operations in JavaScript engines.
  2. Potential Performance Implications:

    • The new StringBuilder implementations in stringbuilder_buffer.mbt and stringbuilder_concat.mbt should be carefully validated for performance, especially in high-throughput scenarios where string concatenation is frequent. The choice between Buffer and direct string concatenation (+ operator) can have significant performance differences.
    • The non-JavaScript implementation (stringbuilder_buffer.mbt) uses a Buffer internally, which is likely to be more efficient for large-scale concatenation due to its mutable nature. However, this needs to be benchmarked against the previous implementation to ensure there are no regressions.
    • The JavaScript-specific implementation (stringbuilder_concat.mbt) directly concatenates strings, which might be optimized by the JavaScript engine but could still lead to performance bottlenecks if not handled properly.
  3. Error Handling and Validation:

    • The substring function and its related error-prone conditions have been moved and possibly consolidated. This is a good practice for maintaining code consistency and reducing duplication.
    • Ensure that the error messages and the conditions under which they are thrown are consistent and provide clear guidance for debugging. The new implementations should pass existing tests and any new tests should be added to cover edge cases, especially those related to negative indices and out-of-bound errors.

Recommendations:

  1. Performance Testing:

    • Conduct thorough performance testing to ensure that the new StringBuilder implementations do not introduce performance regressions, especially in scenarios that involve heavy string manipulation.
  2. Code Review and Validation:

    • Review the new implementations for any potential edge cases or inconsistencies in behavior compared to the old Buffer-based implementations.
    • Ensure all new and modified functions are covered by unit tests to catch any regressions or bugs introduced by the refactoring.
  3. Documentation Updates:

    • Update any relevant documentation to reflect the new StringBuilder type and its usage, including any performance considerations for different environments.

By addressing these points, the transition to using StringBuilder should result in clearer, more maintainable code with minimal impact on performance.

@hackwaly
Copy link
Contributor Author

hackwaly commented Sep 26, 2024

By replace the internal StringBuilder previously used in json package. The performance @json.parse on wasm also be improved after this MR.

@hackwaly hackwaly requested a review from bobzhang October 8, 2024 12:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants