Skip to content

Commit

Permalink
Cache last parsed host
Browse files Browse the repository at this point in the history
Artax re-parses the same host multiple times, because it's parsed in Artax, then parsed in HttpSocketPool, then parsed in BasicSocketPool. All calls happen synchronously, so it makes sense to cache exactly the last parsed host. Other similar uses might benefit, too.

I'm not sure about benefits for non-benchmarks, but it brings significant benefits in benchmark situations.
  • Loading branch information
kelunik committed Oct 11, 2017
1 parent 0ebec68 commit e19d324
Showing 1 changed file with 31 additions and 16 deletions.
47 changes: 31 additions & 16 deletions src/Uri.php
Expand Up @@ -6,6 +6,11 @@
* Provides URI parsing and can resolve URIs.
*/
final class Uri {
private static $lastHost;
private static $lastHostNormalized;
private static $lastHostIpV4;
private static $lastHostIpV6;

private $defaultPortMap = [
"http" => 80,
"https" => 443,
Expand Down Expand Up @@ -45,23 +50,33 @@ public function __construct(string $uri) {
// "schemes are case-insensitive"
$this->scheme = \strtolower($this->scheme);

// http://www.apps.ietf.org/rfc/rfc3986.html#sec-3.2.2
// "Although host is case-insensitive, producers and normalizers should use lowercase for
// registered names and hexadecimal addresses for the sake of uniformity"
if ($inAddr = @\inet_pton(\trim($this->host, "[]"))) {
$this->host = \strtolower($this->host);

if (isset($inAddr[4])) {
$this->isIpV6 = true;
} else {
$this->isIpV4 = true;
}
} elseif ($this->host) {
try {
$this->host = normalizeDnsName($this->host);
} catch (InvalidDnsNameException $e) {
throw new InvalidUriException("Invalid URI: Invalid host: {$this->host}", 0, $e);
if ($this->host === self::$lastHost) {
$this->host = self::$lastHostNormalized;
$this->isIpV4 = self::$lastHostIpV4;
$this->isIpV6 = self::$lastHostIpV6;
} else {
// http://www.apps.ietf.org/rfc/rfc3986.html#sec-3.2.2
// "Although host is case-insensitive, producers and normalizers should use lowercase for
// registered names and hexadecimal addresses for the sake of uniformity"
if ($inAddr = @\inet_pton(\trim($this->host, "[]"))) {
$this->host = \strtolower($this->host);

if (isset($inAddr[4])) {
$this->isIpV6 = true;
} else {
$this->isIpV4 = true;
}
} elseif ($this->host) {
try {
$this->host = normalizeDnsName($this->host);
} catch (InvalidDnsNameException $e) {
throw new InvalidUriException("Invalid URI: Invalid host: {$this->host}", 0, $e);
}
}

self::$lastHostNormalized = $this->host;
self::$lastHostIpV4 = $this->isIpV4;
self::$lastHostIpV6 = $this->isIpV6;
}

if ($this->port === 0) {
Expand Down

0 comments on commit e19d324

Please sign in to comment.