Skip to content

Commit

Permalink
Avoid calling Headers#env_name when static header
Browse files Browse the repository at this point in the history
`env_name` has to transform given strings into the `HTTP_` type headers
that are put in the Rack env. This involves at least one String
allocation and a few additional transformations performed on the string.

This commit avoids the extra allocations/transformations by precomputing
some request header strings so that `env_name` can be avoided. The
places changed here show up in a basic controller request, but there may
be other places that could be changed as well.
  • Loading branch information
skipkayhil committed Jun 28, 2024
1 parent 6045f25 commit 7fe6675
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 3 deletions.
6 changes: 4 additions & 2 deletions actionpack/lib/action_dispatch/http/request.rb
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,8 @@ def #{env.delete_prefix("HTTP_").downcase} # def accept_charset
METHOD
end

TRANSFER_ENCODING = "HTTP_TRANSFER_ENCODING" # :nodoc:

def self.empty
new({})
end
Expand Down Expand Up @@ -282,7 +284,7 @@ def media_type

# Returns the content length of the request as an integer.
def content_length
return raw_post.bytesize if headers.key?("Transfer-Encoding")
return raw_post.bytesize if has_header?(TRANSFER_ENCODING)
super.to_i
end

Expand Down Expand Up @@ -467,7 +469,7 @@ def default_session

def read_body_stream
reset_stream(body_stream) do
if headers.key?("Transfer-Encoding")
if has_header?(TRANSFER_ENCODING)
body_stream.read # Read body stream until EOF if "Transfer-Encoding" is present
else
body_stream.read(content_length)
Expand Down
3 changes: 2 additions & 1 deletion actionpack/lib/action_dispatch/middleware/request_id.rb
Original file line number Diff line number Diff line change
Expand Up @@ -25,11 +25,12 @@ class RequestId
def initialize(app, header:)
@app = app
@header = header
@env_header = "HTTP_#{header.upcase.tr("-", "_")}"
end

def call(env)
req = ActionDispatch::Request.new env
req.request_id = make_request_id(req.headers[@header])
req.request_id = make_request_id(req.get_header(@env_header))
@app.call(env).tap { |_status, headers, _body| headers[@header] = req.request_id }
end

Expand Down

0 comments on commit 7fe6675

Please sign in to comment.