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

Improve Array#to_js speed #281

Merged
merged 1 commit into from
Oct 31, 2023
Merged

Improve Array#to_js speed #281

merged 1 commit into from
Oct 31, 2023

Conversation

krmbn0576
Copy link
Contributor

Hi I am struggling with a large overhead when porting large sized arrays from Ruby to JS.
I found that this is caused by the implicit conversion Array#to_js and so I made this performance improvement.

measurement code below:

require "js"

JS.global[:console].time "old"
new_array = JS.eval("return []")
Array.new(10000).each do |element|
  new_array.push element
end
JS.global[:console].timeEnd "old" # 174.81494140625 ms

JS.global[:console].time "new"
new_array = JS.eval("return []")
Array.new(10000).each_slice(100) do |elements|
  new_array.push *elements
end
JS.global[:console].timeEnd "new" # 14.78466796875 ms

Copy link
Member

@kateinoigakukun kateinoigakukun left a comment

Choose a reason for hiding this comment

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

Good finding, thank you! I slightly changed it to avoid unnecessary slicing. Confirmed it's still blazingly faster than the existing one.

old: 147.285ms
new: 6.113ms

Convert Ruby elements to JS elements while preparing JS method call
under `JS::Object#call` instead of converting at Ruby level for each
element.
@kateinoigakukun kateinoigakukun enabled auto-merge (rebase) October 31, 2023 17:07
@kateinoigakukun kateinoigakukun merged commit c0be5fd into ruby:main Oct 31, 2023
29 of 30 checks passed
@krmbn0576 krmbn0576 deleted the patch-1 branch December 14, 2023 16:42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Development

Successfully merging this pull request may close these issues.

2 participants