Send a blank email to [email protected] to get a copy of this message
Hello, internals!
Today I was looking at PSR-7 and discovered this part of code:
$body = new StringStream(json_encode(['tasks' => [
'Code',
'Coffee',
]]));;
$request = $baseRequest
->withUri($uri->withPath('/tasks/user/' . $userId))
->withMethod('POST')
->withHeader('Content-Type' => 'application/json')
->withBody($body);
$response = $client->send($request);
What is wrong here? Emulated immutability. All methods will create a
separate instance of request, so
$baseRequest->withUri()->withMethod()->withHeader()->withBody() will create
total 5 object instances. It's a memory overhead and time consumption for
each method call.
What I want to discuss is true immutability flag for variables and
parameters. There are a lot of languages that use "final" or "const"
keywords to prevent modification of variables. We can use this approach by
extending language syntax as following:
const $text = "Some message"; // defines an immutable variable that can not
be modified.
$text .= "foo"; // Exception: can not change the immutable variable
class Test {
public final $value; // final keyword defines immutable property, but
it isn't initialized yet so allows only one assignment, then will be
immutable
public function __construct(const $value) // Argument is declared as
immutable with "const" keyword, can not be changed in the function body
{
$this->value = $value;
// $value = 456; // will throw an exception
}
}
$obj = new Test(42);
echo $obj->value; // Direct access to the property, result is 42
$obj->value = 100; // Exception: can not change the immutable (final)
property
Immutable variable can not be made mutable, but it can be assigned to the
separate mutable variable (copy on write). Example:
const $text = "Some message";
$anotherText = $text;
$anotherText .= "modified"
On the engine level this immutable variables and parameters can be
effectively optimized by using IS_TYPE_IMMUTABLE for zval. This can result
in achieving better performance and various JIT-optimizations.
Thoughts?