Issue #17111 has been reported by tonytonyjan (Wei-Hang Jian).

----------------------------------------
Feature #17111: Improve performance of Net::HTTPHeader#set_form by 40%
https://bugs.ruby-lang.org/issues/17111

* Author: tonytonyjan (Wei-Hang Jian)
* Status: Open
* Priority: Normal
----------------------------------------
## diff

```diff
diff --git a/lib/net/http/header.rb b/lib/net/http/header.rb
index a8901e7..3f1a008 100644
--- a/lib/net/http/header.rb
+++ b/lib/net/http/header.rb
@@ -475,9 +475,8 @@ def set_form(params, enctype='application/x-www-form-urlencoded', formopt={})
     @body = nil
     @body_stream = nil
     @form_option = formopt
-    case enctype
-    when /\Aapplication\/x-www-form-urlencoded\z/i,
-      /\Amultipart\/form-data\z/i
+    case enctype.downcase
+    when 'application/x-www-form-urlencoded', 'multipart/form-data'
       self.content_type = enctype
     else
       raise ArgumentError, "invalid enctype: #{enctype}"
```

## benchmark

```ruby
require 'benchmark'
require 'net/http'

module Net::HTTPHeader
  def set_form2(params, enctype = 'application/x-www-form-urlencoded', formopt = {})
    @body_data = params
    @body = nil
    @body_stream = nil
    @form_option = formopt
    case enctype.downcase
    when 'application/x-www-form-urlencoded', 'multipart/form-data'
      self.content_type = enctype
    else
      raise ArgumentError, "invalid enctype: #{enctype}"
    end
  end
end

n = 500_000
request = Net::HTTP::Post.new('/')
Benchmark.bm do |x|
  GC.disable
  x.report { n.times { request.set_form [] } }
  x.report { n.times { request.set_form2 [] } }
end
```

```
       user     system      total        real
   0.777054   0.101768   0.878822 (  0.880472)
   0.539860   0.088957   0.628817 (  0.630178)
```

I don't see any test for `#set_form` in `test/net/http/test_httpheader.rb`, let me know if I need to add more tests, thanks!

---Files--------------------------------
patch-1.diff (621 Bytes)


-- 
https://bugs.ruby-lang.org/

Unsubscribe: <mailto:ruby-core-request / ruby-lang.org?subject=unsubscribe>
<http://lists.ruby-lang.org/cgi-bin/mailman/options/ruby-core>