From 3e3e3aed87fd5362368f22aad87f1e5f65b04f5d Mon Sep 17 00:00:00 2001 From: hadley Date: Tue, 24 May 2016 08:51:52 -0500 Subject: [PATCH] Cache default_ua on package load The default_ua function is called on every request and involves calls to the slow base function packageDescription. Depending on the use, this can account for up to 40% of the client-side CPU time which is a lot when using over a loopback connection (e.g. etcd, RNeo4j). Because this information is unlikely to change during a session (and is infomative for the server and likely ignored anyway) computing it once and reusing it seems safe). By @richfitz, closes #322. --- NEWS.md | 4 ++++ R/config.r | 17 +++++++++++------ 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/NEWS.md b/NEWS.md index 42b5df55..96af4a7c 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,9 @@ # httr 1.1.0.9000 +* The default user agent string is now computed once and cached. This + is a small performance improvement, but important for local connections + (#322, @richfitz). + * New `encode = "raw"` allows you to do your own encoding for requests with bodies. diff --git a/R/config.r b/R/config.r index 8adb1b05..a6665db5 100644 --- a/R/config.r +++ b/R/config.r @@ -130,13 +130,18 @@ curl_docs <- function(x) { BROWSE(url) } +cache <- new.env(parent = emptyenv()) +cache$default_ua <- NULL + default_ua <- function() { - versions <- c( - libcurl = curl::curl_version()$version, - `r-curl` = as.character(utils::packageVersion("curl")), - httr = as.character(utils::packageVersion("httr")) - ) - paste0(names(versions), "/", versions, collapse = " ") + if (is.null(cache$default_ua)) { + versions <- c( + libcurl = curl::curl_version()$version, + `r-curl` = as.character(utils::packageVersion("curl")), + httr = as.character(utils::packageVersion("httr"))) + cache$default_ua <- paste0(names(versions), "/", versions, collapse = " ") + } + cache$default_ua } #' Set (and reset) global httr configuration.