Skip to content

Conversation

@ProGM
Copy link

@ProGM ProGM commented May 18, 2018

I've noticed a peak of memory allocations in this file by using derailed gem

       800  /Users/progm/.rbenv/versions/2.3.5/lib/ruby/gems/2.3.0/gems/deface-1.0.2/lib/deface/search.rb:13
       400  /Users/progm/.rbenv/versions/2.3.5/lib/ruby/gems/2.3.0/gems/deface-1.0.2/lib/deface/override.rb:189

That could be simply fixed using a .freeze.

  • Freezing empty strings
  • use compact! instead of compact

Summary by CodeRabbit

  • Refactor
    • Improved internal logic for combining digest strings and processing search results, resulting in cleaner and more efficient code execution. No changes to user-facing features or functionality.

def self.digest(details)
overrides = self.find(details)
to_hash = overrides.inject('') { |digest, override| digest << override.digest }
to_hash = overrides.inject(''.freeze) { |digest, override| digest << override.digest }
Copy link
Collaborator

Choose a reason for hiding this comment

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

This needs to become a +=.

Copy link
Author

Choose a reason for hiding this comment

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

Do you mean overrides.inject('') { |digest, override| digest += override.digest } ?

Uhm maybe also overrides.map(&:digest).join?

Copy link
Collaborator

Choose a reason for hiding this comment

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

@ProGM I mean:

overrides.inject(''.freeze) { |digest, override| digest += override.digest }

<< will fail on a frozen string because it attempts to mutate the object, so you need to create a new string every time. I'm not sure if that will negate the performance benefits of using .freeze though.

ProGM added 2 commits June 16, 2025 11:44
* Freezing empty string
* use `compact!` instead of compact
@elia elia force-pushed the memory-allocations branch from 43b8ed0 to 98ce01f Compare June 16, 2025 09:51
@coderabbitai
Copy link

coderabbitai bot commented Jun 16, 2025

Walkthrough

The changes refactor internal logic in two methods: one in lib/deface/override.rb for digest string construction, and another in lib/deface/search.rb for result array processing. Both updates simplify the implementation without modifying method signatures or altering the public interface or control flow.

Changes

File(s) Change Summary
lib/deface/override.rb Refactored digest string construction in self.digest(details) to use map(&:digest).join instead of inject for concatenation.
lib/deface/search.rb Modified find method to explicitly freeze empty strings in gsub! and to flatten/compact result arrays earlier in the process.

Poem

In the warren of code, we hop and we play,
Refactoring strings in a more elegant way.
Arrays now flatten with a compact little cheer,
Digests join paws, their purpose crystal clear.
With every small tweak, our code’s more refined—
A rabbit’s delight, in the logic we find!
🐇✨

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.
    • Explain this complex logic.
    • 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 explain this code block.
    • @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 explain its main purpose.
    • @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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this 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.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
lib/deface/search.rb (1)

18-21: Minor allocation win still possible – use destructive flatten!.

result = result.flatten creates a second array before you immediately mutate it with compact!.
You can avoid that intermediate allocation:

-result = result.flatten
-result.compact!
+result.flatten!
+result.compact!

flatten! returns nil when no modification occurs, so keep using the receiver (result) afterwards just like you do with compact!.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 6bf18df and 98ce01f.

📒 Files selected for processing (2)
  • lib/deface/override.rb (1 hunks)
  • lib/deface/search.rb (1 hunks)
🧰 Additional context used
🧬 Code Graph Analysis (1)
lib/deface/search.rb (3)
lib/deface/dsl/context.rb (1)
  • virtual_path (18-20)
lib/deface/override.rb (1)
  • all (203-205)
spec/spec_helper.rb (1)
  • all (106-108)
🔇 Additional comments (2)
lib/deface/search.rb (1)

13-13: Nice touch freezing the replacement string.

Using ''.freeze avoids repeated allocations of identical empty strings during the gsub! loop.

lib/deface/override.rb (1)

198-200: Digest generation is clearer and allocation-friendly – LGTM.

Building the digest with map(&:digest).join removes repeated string reallocations seen with += and keeps the code concise.

Comment on lines 10 to 14
virtual_path = details[:virtual_path].dup
return [] if virtual_path.nil?

[/^\//, /\.\w+\z/].each { |regex| virtual_path.gsub!(regex, '') }
[/^\//, /\.\w+\z/].each { |regex| virtual_path.gsub!(regex, ''.freeze) }

Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

dup is called before the nil-check – potential NoMethodError.

If details[:virtual_path] is nil, the call to .dup (line 10) will raise before you reach the guard on line 11.
Move the fetch/early-return ahead of the dup, e.g.:

-virtual_path = details[:virtual_path].dup
-return [] if virtual_path.nil?
+virtual_path = details[:virtual_path]
+return [] unless virtual_path
+virtual_path = virtual_path.dup
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
virtual_path = details[:virtual_path].dup
return [] if virtual_path.nil?
[/^\//, /\.\w+\z/].each { |regex| virtual_path.gsub!(regex, '') }
[/^\//, /\.\w+\z/].each { |regex| virtual_path.gsub!(regex, ''.freeze) }
virtual_path = details[:virtual_path]
return [] unless virtual_path
virtual_path = virtual_path.dup
[/^\//, /\.\w+\z/].each { |regex| virtual_path.gsub!(regex, ''.freeze) }
🤖 Prompt for AI Agents
In lib/deface/search.rb around lines 10 to 14, the code calls .dup on
details[:virtual_path] before checking if it is nil, which can cause a
NoMethodError. To fix this, first check if details[:virtual_path] is nil and
return an empty array early if so, then call .dup on it after the nil check to
avoid errors.

elia added a commit that referenced this pull request Jul 31, 2025
- Freeze static objects
- Avoid useless ops

Inspired by #184
@elia elia closed this in #244 Jul 31, 2025
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.

2 participants