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

Merged
merged 6 commits into from
Oct 9, 2024

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 3372

Details

  • 30 of 37 (81.08%) changed or added relevant lines in 10 files are covered.
  • No unchanged relevant lines lost coverage.
  • Overall coverage decreased (-0.08%) to 83.165%

Changes Missing Coverage Covered Lines Changed/Added Lines %
builtin/assert.mbt 0 1 0.0%
builtin/autoloc.mbt 0 1 0.0%
builtin/stringbuilder_buffer.mbt 10 11 90.91%
builtin/string.mbt 2 6 33.33%
Totals Coverage Status
Change from base Build 3370: -0.08%
Covered Lines: 4105
Relevant Lines: 4936

💛 - 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, here are three potential issues or areas of improvement I've identified:

  1. Inconsistent Use of Buffer and StringBuilder:

    • There are multiple instances where Buffer::new is being replaced with StringBuilder::new. This suggests a transition from using Buffer to StringBuilder for string operations. However, there are inconsistencies in how these replacements are handled. For example, in some cases, the size_hint parameter is being passed directly to StringBuilder::new, while in others, it seems to be omitted or handled differently.
    • Suggestion: Ensure that all instances of Buffer are replaced with StringBuilder consistently across the codebase. Also, verify that the size_hint parameter is correctly handled in all cases to optimize performance.
  2. Potential Overhead in String Concatenation:

    • In the new file builtin/stringbuilder_concat.mbt, the StringBuilder type is implemented using string concatenation (self.val += str). While this is straightforward, it can lead to performance issues if the strings being concatenated are large or if there are many concatenations.
    • Suggestion: Consider optimizing the string concatenation operations, especially for large strings or frequent concatenations. This could involve using more efficient data structures or algorithms to manage the string building process.
  3. Potential Bugs in Substring Function:

    • In the new file builtin/string.mbt, the substring function has several boundary checks (e.g., checking if start and end are within bounds). However, these checks might not cover all edge cases, especially those involving negative indices or indices that exceed the string length.
    • Suggestion: Thoroughly test the substring function to ensure it handles all edge cases correctly. Consider adding additional checks or tests to cover scenarios where start or end might be negative or exceed the string length.

Overall, these observations highlight the importance of ensuring consistency, optimizing performance, and thoroughly testing new functionalities or changes in the codebase. By addressing these issues, the code can become more robust, efficient, and less prone to bugs.

@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.

@bobzhang
Copy link
Contributor

bobzhang commented Oct 9, 2024

Per discussions offline, we agree to make a reasonably fast StringBuilder package on all platform.

  1. StringBuilder should not depend on Buffer
  2. we will move Buffer out of builtin package

@hackwaly hackwaly marked this pull request as draft October 9, 2024 07:32
@hackwaly hackwaly marked this pull request as ready for review October 9, 2024 07:32
@hackwaly
Copy link
Contributor Author

hackwaly commented Oct 9, 2024

Now StringBuilder doesn't depend on Buffer.

@bobzhang bobzhang merged commit ba3d184 into main Oct 9, 2024
12 checks passed
@bobzhang bobzhang deleted the yuxiang/string-builder branch October 9, 2024 08:36
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