# Analysis of property visibility, immutability, and cloning proposals

- Thread: https://externals.io/message/112627
- Original archive: https://news-web.php.net/php.internals/112627
- Started by Larry Garfield on 2020-12-28T20:23:56+00:00
- Messages: 46
- Page 1 of 2: messages 1 to 25 (25 per page, add `?page=N` to the URL)
- Next page: https://externals.io/message/112627.md?page=2
- Reply by email to internals@lists.php.net
- More for agents: search with https://externals.io/search.md?q={query} · RFCs at https://externals.io/rfc.md · JSON API at https://externals.io/api · documentation at https://externals.io/llms.txt

---

## #112627 — Larry Garfield — 2020-12-28T20:23:56+00:00

URL: https://externals.io/message/112627#112627

There's been a number of discussions of late around property visibility and how to make objects more immutable.  Since it seems to have been well-received in the past, I decided to do a complete analysis and context of the various things that have been floated about recently.

The full writeup is here:

https://peakd.com/hive-168588/@crell/object-properties-and-immutability

I hope it proves stimulating, at least of discussion and not naps.

-- 
  Larry Garfield
  larry@garfieldtech.com

---

## #112630 — Marc — 2020-12-29T08:26:01+00:00

URL: https://externals.io/message/112627#112630 · In reply to: #112627

> There's been a number of discussions of late around property visibility and how to make objects more immutable.  Since it seems to have been well-received in the past, I decided to do a complete analysis and context of the various things that have been floated about recently.
>
> The full writeup is here:
>
> https://peakd.com/hive-168588/@crell/object-properties-and-immutability
>
> I hope it proves stimulating, at least of discussion and not naps.
>

Thanks for the nice write up Larry!

Is there a reason you didn't mention the proposal for immutable classes?
(probably because it never went into a final RFC)

https://externals.io/message/94913#94913

https://externals.io/message/79180#79180

---

## #112633 — olleharstedt@gmail.com — 2020-12-29T10:28:41+00:00

URL: https://externals.io/message/112627#112633 · In reply to: #112630

2020-12-29 8:26 GMT, Marc <marc@mabe.berlin>:
>
> 
> > […]
>
> Thanks for the nice write up Larry!
>
> Is there a reason you didn't mention the proposal for immutable classes?
> (probably because it never went into a final RFC)
>
> https://externals.io/message/94913#94913
>
> https://externals.io/message/79180#79180
>
> --
> 
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>

I just want to mention that immutability might be applied too
liberally in the current discourse, and in some cases, what you really
want is *non-aliasing*, that is, uniqueness, to solve problems related
to immutability. I think methods like `withX` is an anti-pattern, in
fact, and a symptom that you do not *really* want immutability, but
rather uniqueness, at least in some cases.

Olle

---

## #112635 — Larry Garfield — 2020-12-29T15:38:01+00:00

URL: https://externals.io/message/112627#112635 · In reply to: #112630

> 
> 
> > […]
> 
> Thanks for the nice write up Larry!
> 
> Is there a reason you didn't mention the proposal for immutable classes?
> (probably because it never went into a final RFC)
> 
> https://externals.io/message/94913#94913
> 
> https://externals.io/message/79180#79180

Two main reasons:

1) It's not been discussed recently (see how old the dates are on those messages), so I wasn't thinking about it.

2) An immutable class would in all practicality be the same as a class where all the properties are initonly (or writeonce, but that was already rejected).  So any arguments for/against initonly apply in aggregate to an immutable class.

--Larry Garfield

---

## #112643 — olleharstedt@gmail.com — 2020-12-29T18:38:51+00:00

URL: https://externals.io/message/112627#112643 · In reply to: #112635

2020-12-29 15:38 GMT, Larry Garfield <larry@garfieldtech.com>:
> 
> > […]
>
> Two main reasons:
>
> 1) It's not been discussed recently (see how old the dates are on those
> messages), so I wasn't thinking about it.
>
> 2) An immutable class would in all practicality be the same as a class where
> all the properties are initonly (or writeonce, but that was already
> rejected).  So any arguments for/against initonly apply in aggregate to an
> immutable class.
>
> --Larry Garfield
>
> --
> 
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>

Instead of shoe-horning everything into the PHP object system, did
anyone consider adding support for records instead, which would always
be immutable, and could support the spread operator for cloning-with
similar as in JavaScript or OCaml? They could be based on PHP arrays
and thus be passed by value.

Olle

---

## #112647 — Thomas Nunninger — 2020-12-29T21:07:56+00:00

URL: https://externals.io/message/112627#112647 · In reply to: #112627

Am 28.12.20 um 21:23 schrieb Larry Garfield:
> There's been a number of discussions of late around property visibility and how to make objects more immutable.  Since it seems to have been well-received in the past, I decided to do a complete analysis and context of the various things that have been floated about recently.
> 
> The full writeup is here:
> 
> https://peakd.com/hive-168588/@crell/object-properties-and-immutability
> 
> I hope it proves stimulating, at least of discussion and not naps.

A really nice writeup and interesting to read.

But I have a question:

> We then end up with the following combinations:
> 
> * public read, private write
> * public read, private read, init write
> * public none, private write
> * public none, private read
> * public none, private read, init write

What is the difference between

  (a) "public none, private read" and
  (b) "public none, private read, init"

write"? When will (a) be initialized?

And if there is really a useful case for (a) why is there no "public 
read, private read"?

Regards

Thomas

---

## #112648 — Rowan Tommins — 2020-12-29T21:36:25+00:00

URL: https://externals.io/message/112627#112648 · In reply to: #112633

> I just want to mention that immutability might be applied too
> liberally in the current discourse, and in some cases, what you really
> want is*non-aliasing*, that is, uniqueness, to solve problems related
> to immutability. I think methods like `withX` is an anti-pattern, in
> fact, and a symptom that you do not*really*  want immutability, but
> rather uniqueness, at least in some cases.


Hi Olle,

I'm afraid I don't follow what you mean by "non-aliasing" and 
"uniqueness" here. Could you clarify, perhaps with some examples?

Cheers,

-- 
Rowan Tommins
[IMSoP]

---

## #112650 — Rowan Tommins — 2020-12-29T22:43:18+00:00

URL: https://externals.io/message/112627#112650 · In reply to: #112643

> Instead of shoe-horning everything into the PHP object system, did
> anyone consider adding support for records instead, which would always
> be immutable, and could support the spread operator for cloning-with
> similar as in JavaScript or OCaml? They could be based on PHP arrays
> and thus be passed by value.


While we could create a brand new "record" or "struct" type, I think 
there are a few reasons to think it would end up *looking* more like 
objects than arrays:

- we have an established syntax for declaring types of object (class Foo 
{...}), and none for declaring types of array
- the 'bar' in $foo['bar'] is an expression, implying dynamic options; 
the bar in $foo->bar is a bare identifier, implying statically defined 
options
- similarly, we have a syntax for creating object instances, with 
statically analysable members: new Foo(bar: 42)


The spread operator could be made to work with either style, if we 
preferred it to using "clone ... with ...":

- ['bar'=>69, ...$existingFoo]
- new Foo(bar: 69, ...$existingFoo)


However, arrays arguably already have a clone-with syntax, more normally 
thought of as "copy-on-write". Rather than "mutable with special logic 
to pass and assign by value", I think you can model their behaviour as 
"immutable with special logic to clone with modifications":

$foo = ['bar'=>42, 'baz'=>101];
$newFoo = $foo; // lazy assignment by value is indistinguishable from 
assignment by pointer
$newFoo['bar'] = 69; // $newFoo is a modified clone of $foo
$newFoo['bar'] = 72; // mutating $newFoo in place is indistinguishable 
from creating and assigning another modified clone


In theory, "records" could have this ability with object-like syntax:

$foo = new Foo(bar: 42, baz: 101);
$newFoo = $foo;
$newFoo->bar = 69; // $newFoo is a modified clone
$newFoo->bar = 72; // can be optimised as in-place modification, but 
conceptually cloning again


In the simple case, that's equivalent to a clone-with:

$foo = new Foo(bar: 42, baz: 101);
$newFoo = clone $foo with { bar: 69 };
$newFoo = clone $newFoo with { bar: 72 }; // can probably be optimised 
the same way as the above examples


It would allow more complex modifications, though, such as deep 
modification:

$foo = new Foo(bar: new Bar(name: 'Bob'));
$newFoo = $foo;
$newFoo->bar->name = 'Robert';

That last line would do the same as this:

$newFoo = clone $newFoo with { bar: clone $newFoo->bar with { name: 
'Robert' }};

How desirable that is, and how it fits with the use cases in Larry's 
post, I'm not sure.


Regards,

-- 
Rowan Tommins
[IMSoP]

---

## #112659 — olleharstedt@gmail.com — 2020-12-30T13:00:51+00:00

URL: https://externals.io/message/112627#112659 · In reply to: #112650

2020-12-29 22:43 GMT, Rowan Tommins <rowan.collins@gmail.com>:
> 
> > […]
>
>
> While we could create a brand new "record" or "struct" type, I think
> there are a few reasons to think it would end up *looking* more like
> objects than arrays:
>
> - we have an established syntax for declaring types of object (class Foo
> {...}), and none for declaring types of array
> - the 'bar' in $foo['bar'] is an expression, implying dynamic options;
> the bar in $foo->bar is a bare identifier, implying statically defined
> options
> - similarly, we have a syntax for creating object instances, with
> statically analysable members: new Foo(bar: 42)
>
>
> The spread operator could be made to work with either style, if we
> preferred it to using "clone ... with ...":
>
> - ['bar'=>69, ...$existingFoo]
> - new Foo(bar: 69, ...$existingFoo)
>
>
> However, arrays arguably already have a clone-with syntax, more normally
> thought of as "copy-on-write". Rather than "mutable with special logic
> to pass and assign by value", I think you can model their behaviour as
> "immutable with special logic to clone with modifications":
>
> $foo = ['bar'=>42, 'baz'=>101];
> $newFoo = $foo; // lazy assignment by value is indistinguishable from
> assignment by pointer
> $newFoo['bar'] = 69; // $newFoo is a modified clone of $foo
> $newFoo['bar'] = 72; // mutating $newFoo in place is indistinguishable
> from creating and assigning another modified clone
>
>
> In theory, "records" could have this ability with object-like syntax:
>
> $foo = new Foo(bar: 42, baz: 101);
> $newFoo = $foo;
> $newFoo->bar = 69; // $newFoo is a modified clone
> $newFoo->bar = 72; // can be optimised as in-place modification, but
> conceptually cloning again
>
>
> In the simple case, that's equivalent to a clone-with:
>
> $foo = new Foo(bar: 42, baz: 101);
> $newFoo = clone $foo with { bar: 69 };
> $newFoo = clone $newFoo with { bar: 72 }; // can probably be optimised
> the same way as the above examples
>
>
> It would allow more complex modifications, though, such as deep
> modification:
>
> $foo = new Foo(bar: new Bar(name: 'Bob'));
> $newFoo = $foo;
> $newFoo->bar->name = 'Robert';
>
> That last line would do the same as this:
>
> $newFoo = clone $newFoo with { bar: clone $newFoo->bar with { name:
> 'Robert' }};
>
> How desirable that is, and how it fits with the use cases in Larry's
> post, I'm not sure.
>
>
> Regards,
>
> --
> Rowan Tommins
> [IMSoP]
>
> --
> 
> To unsubscribe, visit: https://www.php.net/unsub.php
>
>

Good breakdown. One benefit of records is that they can be
structurally typed (instead of nominally, as classes are), but that's
probably never going to happen in PHP. :) Perhaps a `readonly`
attribute is best for now? Compare with the annotation supported by
Psalm: https://psalm.dev/docs/annotating_code/supported_annotations/#psalm-readonly-and-readonly

Olle

---

## #112660 — olleharstedt@gmail.com — 2020-12-30T13:49:31+00:00

URL: https://externals.io/message/112627#112660 · In reply to: #112648

2020-12-29 21:36 GMT, Rowan Tommins <rowan.collins@gmail.com>:
> 
> > […]
>
>
> Hi Olle,
>
> I'm afraid I don't follow what you mean by "non-aliasing" and
> "uniqueness" here. Could you clarify, perhaps with some examples?
>
> Cheers,
>
> --
> Rowan Tommins
> [IMSoP]
>

Wikipedia has an article about aliasing:
https://en.wikipedia.org/wiki/Aliasing_(computing)
Also relevant: https://en.wikipedia.org/wiki/Uniqueness_type

Uniqueness is when you only allow _one_ reference to an object (or
bucket of memory).

$a = new A();
$b = $a;  // Both $a and $b point to the same place in memory, so you
have an alias

Uniqueness and immutability solves similar problems (at least in a GC
language like PHP): Spooky action at a distance, fragile composition,
rep exposure.

The are more advanced systems of ownership than just uniqueness, e.g.
Universe Types, but let's ignore that for now.
https://www.researchgate.net/publication/221321963_Ownership_transfer_in_Universe_Types

Uniqueness has the benefit of being more performant than immutability,
since it leads to less memory copy (but of course it's not certain
this performance gain matters in PHP programs).

You can compare a builder pattern with immutability vs non-aliasing
(uniqueness):

```
// Immutable
$b = new Builder();
$b = $b->withFoo()->withBar()->withBaz();
myfun($b);  // $b is immutable, so $b cannot be modified by myfun()
return $b;
```

```
// Uniqueness
$b = new Builder();  // class Builder is annotated as non-aliasing/unique
$b->addFoo();
$b->addBar();
$b->addBaz();
myfun(clone $b);  // HAVE TO CLONE TO NOT THROW EXCEPTION.
return $b;
```

The guarantee in both above snippets is that myfun() DOES NOT modify
$b before returning it. BUT with immutability, you have to copy $b
three times, with uniqueness only one. That's why I think ownership
system merits some attention, not ONLY immutability. :) Unfortunately,
it can take a looong time to force new concepts like these into common
discourse. Rust helps, obviously. The language Clean has opt-in
uniqueness (I need to read up more on it, tho). Linear types in e.g.
Haskell is also related (but is both more complex and more powerful).

I would like to add an annotation to Psalm, like @psalm-no-alias,
because this is also needed to make type-state sane. But, didn't do
much yet, only some brain farting. :)

Olle

---

## #112671 — Rowan Tommins — 2020-12-30T18:15:31+00:00

URL: https://externals.io/message/112627#112671 · In reply to: #112660

> Uniqueness is when you only allow _one_ reference to an object (or
> bucket of memory).
> [...]
>
> You can compare a builder pattern with immutability vs non-aliasing
> (uniqueness):
>
> ```
> // Immutable
> $b = new Builder();
> $b = $b->withFoo()->withBar()->withBaz();
> myfun($b);  // $b is immutable, so $b cannot be modified by myfun()
> return $b;
> ```
>
> ```
> // Uniqueness
> $b = new Builder();  // class Builder is annotated as non-aliasing/unique
> $b->addFoo();
> $b->addBar();
> $b->addBaz();
> myfun(clone $b);  // HAVE TO CLONE TO NOT THROW EXCEPTION.
> return $b;
> ```


Thanks, I can see how that solves a lot of the same problems, in a very 
robustly analysable way.

However, from a high-level user-friendliness point of view, I think 
"withX" methods are actually more natural than explicitly cloning 
mutable objects.

Consider the case of defining a range: firstly, with plain integers and 
familiar operators:

$start = 1;
$end = $start + 5;

This models integers as immutable values, and + as an operator which 
returns a new instance. If integers were mutable but not aliasable, we 
would instead write something like this:

$start = 1;
$end = clone $start;
$end += 5; // where += would be an in-place modification, not a 
short-hand for assignment

I think the first more naturally expresses the desired algorithm. It's 
therefore natural to want the same for a range of dates:

$start = MyDate::today();
$end = $start->withAddedDays(5);

vs

$start = MyDate::today();
$end = clone $start;
$end->addDays(5);


To put it a different way, value types naturally form *expressions*, 
which mutable objects model clumsily. It would be very tedious if we had 
to avoid accidentally mutating the speed of light:

$e = (clone $m) * ((clone $c) ** 2);


> The guarantee in both above snippets is that myfun() DOES NOT modify
> $b before returning it. BUT with immutability, you have to copy $b
> three times, with uniqueness only one.


I wonder if that difference can be optimised out by the 
compiler/OpCache: detect clones that immediately replace their original, 
and optimise it to an in-place modification. In other words, compile 
$foo = clone $foo with { x: 42 } to $foo->x = 42, even if the clone is 
actually in a "withX" method.


Regards,

-- 
Rowan Tommins
[IMSoP]

---

## #112673 — Larry Garfield — 2020-12-30T18:31:09+00:00

URL: https://externals.io/message/112627#112673 · In reply to: #112671

> 
> > […]
> 
> 
> Thanks, I can see how that solves a lot of the same problems, in a very 
> robustly analysable way.
> 
> However, from a high-level user-friendliness point of view, I think 
> "withX" methods are actually more natural than explicitly cloning 
> mutable objects.
> 
> Consider the case of defining a range: firstly, with plain integers and 
> familiar operators:
> 
> $start = 1;
> $end = $start + 5;
> 
> This models integers as immutable values, and + as an operator which 
> returns a new instance. If integers were mutable but not aliasable, we 
> would instead write something like this:
> 
> $start = 1;
> $end = clone $start;
> $end += 5; // where += would be an in-place modification, not a 
> short-hand for assignment
> 
> I think the first more naturally expresses the desired algorithm. It's 
> therefore natural to want the same for a range of dates:
> 
> $start = MyDate::today();
> $end = $start->withAddedDays(5);
> 
> vs
> 
> $start = MyDate::today();
> $end = clone $start;
> $end->addDays(5);
> 
> 
> To put it a different way, value types naturally form *expressions*, 
> which mutable objects model clumsily. It would be very tedious if we had 
> to avoid accidentally mutating the speed of light:
> 
> $e = (clone $m) * ((clone $c) ** 2);
> 
> 
> > […]

That's a good summary of why immutability and with-er methods (or some equivalent) are more ergonomic.

Another point to remember: Because of PHP's copy-on-write behavior, full on immutability doesn't actually waste that much memory.  It does use up some, but far less than you think.  (Again, based on the tests MWOP ran for PSR-7 a ways back.)

> I wonder if that difference can be optimised out by the 
> compiler/OpCache: detect clones that immediately replace their original, 
> and optimise it to an in-place modification. In other words, compile 
> $foo = clone $foo with { x: 42 } to $foo->x = 42, even if the clone is 
> actually in a "withX" method.

In concept, maybe?  That's well above my pay grade. :-)

--Larry Garfield

---

## #112675 — olleharstedt@gmail.com — 2020-12-30T18:42:56+00:00

URL: https://externals.io/message/112627#112675 · In reply to: #112671

2020-12-30 18:15 GMT, Rowan Tommins <rowan.collins@gmail.com>:
> 
> > […]
>
>
> Thanks, I can see how that solves a lot of the same problems, in a very
> robustly analysable way.
>
> However, from a high-level user-friendliness point of view, I think
> "withX" methods are actually more natural than explicitly cloning
> mutable objects.
>
> Consider the case of defining a range: firstly, with plain integers and
> familiar operators:
>
> $start = 1;
> $end = $start + 5;
>
> This models integers as immutable values, and + as an operator which
> returns a new instance. If integers were mutable but not aliasable, we
> would instead write something like this:
>
> $start = 1;
> $end = clone $start;
> $end += 5; // where += would be an in-place modification, not a
> short-hand for assignment
>
> I think the first more naturally expresses the desired algorithm. It's
> therefore natural to want the same for a range of dates:
>
> $start = MyDate::today();
> $end = $start->withAddedDays(5);
>
> vs
>
> $start = MyDate::today();
> $end = clone $start;
> $end->addDays(5);

Sure, this is a good use-case for immutability. :)

>
>
> To put it a different way, value types naturally form *expressions*,
> which mutable objects model clumsily. It would be very tedious if we had
> to avoid accidentally mutating the speed of light:
>
> $e = (clone $m) * ((clone $c) ** 2);

Using a variable on right-hand side does not automatically create an
alias, so in the above case you don't have to use clone.

A more motivating example for uniqueness is perhaps a query builder.

```
$query = (new Query())
  ->select(1)
  ->from('foo')
  ->where(...)
  ->orderBy(..)
  ->limit();
doSomething($query);
doSomethingElse($query);
```

In the above snippet, we don't know if doSomething() will change
$query and cause a bug. The issue can be solved with an immutable
builder, using withSelect(), withWhere(), etc, OR it's solved with
uniqueness, forcing a clone to avoid creating a new alias (passing
$query to a function creates an alias inside that function). The
optimisation is the same as in my previous example, avoiding copying
$query multiple times during build-up.

>
>
> > […]
>
>
> I wonder if that difference can be optimised out by the
> compiler/OpCache: detect clones that immediately replace their original,
> and optimise it to an in-place modification. In other words, compile
> $foo = clone $foo with { x: 42 } to $foo->x = 42, even if the clone is
> actually in a "withX" method.

I guess OCaml/Haskell does stuff like this, since everything is
immutable by default there. Let's ask them? Unless someone here
already knows? :)

Olle

---

## #112676 — olleharstedt@gmail.com — 2020-12-30T18:45:05+00:00

URL: https://externals.io/message/112627#112676 · In reply to: #112673

2020-12-30 18:31 GMT, Larry Garfield <larry@garfieldtech.com>:
> 
> > […]
>
> That's a good summary of why immutability and with-er methods (or some
> equivalent) are more ergonomic.
>
> Another point to remember: Because of PHP's copy-on-write behavior, full on
> immutability doesn't actually waste that much memory.  It does use up some,
> but far less than you think.  (Again, based on the tests MWOP ran for PSR-7
> a ways back.)

I thought copy-on-write was only for arrays, not objects?

Olle

---

## #112677 — Larry Garfield — 2020-12-30T19:26:25+00:00

URL: https://externals.io/message/112627#112677 · In reply to: #112676

> > […]
> 
> I thought copy-on-write was only for arrays, not objects?
> 
> Olle

Copy on write applies to all values; the caveat is that with objects, the value being copied is the handle that points to an object in memory, rather than the object itself.  That means passing an object by reference can do some seriously unexpected things, which is why you basically never do so.

The point here is that if you have an object with 15 internal properties, it's memory usage is 15 zvals plus one zval for the object, plus one zval for the variable that points to it.  (I'm over-simplifying here.  A lot.)  If you pass it to a function, only the one zval for the handle is duplicated, which is the same as for an integer.

If you clone the object, you don't duplicate 15+1 zvals.  You duplicate just the one zval for the object itself, which reuses the existing 15 internal property entries.  If in the new object you then update just the third one, PHP then duplicates just that one internal zval and modifies the new one.  So you still are using only 18 zvals, not 36 zvals.  (Engine people: Yes, I am *very* over-simplifying.  I know.)

Basically, what in most languages would require manually implementing "immutable data structures" we get for free in PHP, which is seriously sweet.

The net result is that a with-er chain like this:

$foo2 = $foo->withBar('x')->withBaz('y')->withBeep('z');

is way, way less expensive than it looks, both on memory and CPU.  It is more expensive than setters, but not by much.

That's why I don't think the distinction between unique and immutable mentioned up-thread is that big of a deal in PHP, specifically.  Yes, they're different things, but the cost of them is not all that different because of CoW, so considering them separately is not as important as it would be in a language that doesn't automatically do CoW in the background for us.

(Whoever in the 90s decided to bake CoW into the engine, thank you.  It's an incredibly nice foundational feature.)

--Larry Garfield

---

## #112678 — Larry Garfield — 2020-12-30T19:30:48+00:00

URL: https://externals.io/message/112627#112678 · In reply to: #112675

> A more motivating example for uniqueness is perhaps a query builder.
> 
> ```
> $query = (new Query())
>   ->select(1)
>   ->from('foo')
>   ->where(...)
>   ->orderBy(..)
>   ->limit();
> doSomething($query);
> doSomethingElse($query);
> ```
> 
> In the above snippet, we don't know if doSomething() will change
> $query and cause a bug. The issue can be solved with an immutable
> builder, using withSelect(), withWhere(), etc, OR it's solved with
> uniqueness, forcing a clone to avoid creating a new alias (passing
> $query to a function creates an alias inside that function). The
> optimisation is the same as in my previous example, avoiding copying
> $query multiple times during build-up.

For a query builder, I probably wouldn't make it immutable anyway, myself.  If you really want to force that doSomething() cannot modify the object that is otherwise mutable, calling doSomething(clone $query) already works today and gets that net effect, provided that Query is safe to clone.  (Vis, has no service dependencies, and if it has any dependent value objects then it has a __clone() method that deep clones.)

> > […]

Yes, but with CoW those 3 copies are not that expensive, so we can most of the time ignore them except as a very micro-optimization.  (See previous email.)

--Larry Garfield

---

## #112679 — Chuck Adams — 2020-12-30T19:36:30+00:00

URL: https://externals.io/message/112627#112679 · In reply to: #112677

>
> If you clone the object, you don't duplicate 15+1 zvals.  You duplicate just the one zval for the object itself, which reuses the existing 15 internal property entries.  If in the new object you then update just the third one, PHP then duplicates just that one internal zval and modifies the new one.  So you still are using only 18 zvals, not 36 zvals.  (Engine people: Yes, I am *very* over-simplifying.  I know.)
>

I've pondered hacking in something like perl's bless() to turn arrays
into value objects, but according to this it looks like an object with
clone-on-write behavior would be better, as I'm assuming arrays do a
full shallow copy: given an array of 15 entries, pass it to a
function, change one member, now you're using 15 more zvals, as
opposed to just one with an object.

Am I reading that right?

--c

---

## #112682 — olleharstedt@gmail.com — 2020-12-30T19:50:50+00:00

URL: https://externals.io/message/112627#112682 · In reply to: #112677

>
> > […]
> full on
> > […]
> some,
> > […]
> PSR-7
> > […]
>
> Copy on write applies to all values; the caveat is that with objects, the
> value being copied is the handle that points to an object in memory, rather
> than the object itself.  That means passing an object by reference can do
> some seriously unexpected things, which is why you basically never do so.
>
> The point here is that if you have an object with 15 internal properties,
> it's memory usage is 15 zvals plus one zval for the object, plus one zval
> for the variable that points to it.  (I'm over-simplifying here.  A lot.)
> If you pass it to a function, only the one zval for the handle is
> duplicated, which is the same as for an integer.
>
> If you clone the object, you don't duplicate 15+1 zvals.  You duplicate
> just the one zval for the object itself, which reuses the existing 15
> internal property entries.  If in the new object you then update just the
> third one, PHP then duplicates just that one internal zval and modifies the
> new one.  So you still are using only 18 zvals, not 36 zvals.  (Engine
> people: Yes, I am *very* over-simplifying.  I know.)
>
> Basically, what in most languages would require manually implementing
> "immutable data structures" we get for free in PHP, which is seriously
> sweet.
>
> The net result is that a with-er chain like this:
>
> $foo2 = $foo->withBar('x')->withBaz('y')->withBeep('z');
>
> is way, way less expensive than it looks, both on memory and CPU.  It is
> more expensive than setters, but not by much.
>

Ok. You have a benchmark for this? I can make one otherwise, for the query
example.

It worries me a little that immutablility is pushed into the ecosystem as a
silver bullet. Main reason functional languages are using it is because
ownership is a newer concept, so it hasn't been adapted as much.

---

## #112683 — olleharstedt@gmail.com — 2020-12-30T20:16:58+00:00

URL: https://externals.io/message/112627#112683 · In reply to: #112682

2020-12-30 19:50 GMT, Olle Härstedt <olleharstedt@gmail.com>:
> 
>
> > […]
>
> Ok. You have a benchmark for this? I can make one otherwise, for the query
> example.
>
> It worries me a little that immutablility is pushed into the ecosystem as a
> silver bullet. Main reason functional languages are using it is because
> ownership is a newer concept, so it hasn't been adapted as much.

Tiny benchmark here:
https://gist.github.com/olleharstedt/eaaf1dd40be541f84aa0f3954a0ea54a

Running this on my ARM machine with PHP 7.2 gives ~1.2s for the
immutable loop, ~0.35s for the mutable one, meaning immutability is
~3x as expensive performance wise. And this is for a SMALL object - I
suspect the performance hit will grow the bigger the class gets (more
properties to clone). Correct me if I'm wrong. :/

Olle

---

## #112685 — Larry Garfield — 2020-12-30T20:37:58+00:00

URL: https://externals.io/message/112627#112685 · In reply to: #112683

> > […]
> 
> Tiny benchmark here:
> https://gist.github.com/olleharstedt/eaaf1dd40be541f84aa0f3954a0ea54a
> 
> Running this on my ARM machine with PHP 7.2 gives ~1.2s for the
> immutable loop, ~0.35s for the mutable one, meaning immutability is
> ~3x as expensive performance wise. And this is for a SMALL object - I
> suspect the performance hit will grow the bigger the class gets (more
> properties to clone). Correct me if I'm wrong. :/


That's not a valid benchmark; it's comparing cloning and method invocation against just property sets.  The method calls are chewing up most of the time there.

Here's a more fair comparison on my laptop: https://gist.github.com/Crell/848568124e25c8c83fc4da5455063bab

Which is only ~20% slower.  And that's when dealing with very small numbers, so in most cases you're unlikely to notice a difference unless you really are iterating over something a million times.

I also tossed some big string properties into the class, and while the total time went up a bit the ratio between the two stayed about the same.

--Larry Garfield

---

## #112688 — olleharstedt@gmail.com — 2020-12-30T21:27:31+00:00

URL: https://externals.io/message/112627#112688 · In reply to: #112685

2020-12-30 20:37 GMT, Larry Garfield <larry@garfieldtech.com>:
> 
>
> > […]
>
>
> That's not a valid benchmark; it's comparing cloning and method invocation
> against just property sets.  The method calls are chewing up most of the
> time there.
>
> Here's a more fair comparison on my laptop:
> https://gist.github.com/Crell/848568124e25c8c83fc4da5455063bab
>
> Which is only ~20% slower.  And that's when dealing with very small numbers,
> so in most cases you're unlikely to notice a difference unless you really
> are iterating over something a million times.
>
> I also tossed some big string properties into the class, and while the total
> time went up a bit the ratio between the two stayed about the same.
>
> --Larry Garfield

Oh yeah. Huh. Didn't realize method calling was expensive. :) Another
good reason to not use setters, lol. On my machine it's ~70% slower
with "with" now (running multiple runs, using bash "time").

The performance might matter when frameworks start to adapt patterns
like this. It's already in PSR, with the HTTP message interface etc.
Now I'm curious how OCaml and JS performs with a similar benchmark.
Since they both have tracing GC, and PHP uses ref counting...

---

## #112690 — olleharstedt@gmail.com — 2020-12-30T22:47:00+00:00

URL: https://externals.io/message/112627#112690 · In reply to: #112688

2020-12-30 21:27 GMT, Olle Härstedt <olleharstedt@gmail.com>:
> 2020-12-30 20:37 GMT, Larry Garfield <larry@garfieldtech.com>:
> > […]
>
> Oh yeah. Huh. Didn't realize method calling was expensive. :) Another
> good reason to not use setters, lol. On my machine it's ~70% slower
> with "with" now (running multiple runs, using bash "time").
>
> The performance might matter when frameworks start to adapt patterns
> like this. It's already in PSR, with the HTTP message interface etc.
> Now I'm curious how OCaml and JS performs with a similar benchmark.
> Since they both have tracing GC, and PHP uses ref counting...

Benchmarks for JS and OCaml:
https://gist.github.com/olleharstedt/eaaf1dd40be541f84aa0f3954a0ea54a

In JS, it's 5x more expensive to use spread operator vs mutate the
object fields directly (or maybe node is just not optimized well on
the ARM CPU?). In OCaml, it's a ~10% difference between destructive
update (mutable fields) and cloning. No idea what to take from that.
:)

---

## #112691 — Mike Schinkel — 2020-12-31T00:24:53+00:00

URL: https://externals.io/message/112627#112691 · In reply to: #112671

> 
> 
> 
> > […]
> 
> 
> Thanks, I can see how that solves a lot of the same problems, in a very robustly analysable way.
> 
> However, from a high-level user-friendliness point of view, I think "withX" methods are actually more natural than explicitly cloning mutable objects.


"User-friendliness" of this nature is in the eye of the beholder. 

A different perspective is that "withX" methods require a mental translation where "addX" methods do not, much like how a person whose native language is English will find it a challenge to (or cannot) "think" in French.


> Consider the case of defining a range: firstly, with plain integers and familiar operators:
> 
> $start = 1;
> $end = $start + 5;
> 
> This models integers as immutable values, and + as an operator which returns a new instance. If integers were mutable but not aliasable, we would instead write something like this:
> 
> $start = 1;
> $end = clone $start;
> $end += 5; // where += would be an in-place modification, not a short-hand for assignment
> 
> I think the first more naturally expresses the desired algorithm. It's therefore natural to want the same for a range of dates:
> 
> $start = MyDate::today();
> $end = $start->withAddedDays(5);
> 
> vs
> 
> $start = MyDate::today();
> $end = clone $start;
> $end->addDays(5);


Ignoring that you are comparing apples and oranges (scalars to objects,) the latter is easier to reason about IMO.


> To put it a different way, value types naturally form *expressions*, which mutable objects model clumsily. It would be very tedious if we had to avoid accidentally mutating the speed of light:
> 
> $e = (clone $m) * ((clone $c) ** 2);
> 
> 
> > […]
> 
> 
> I wonder if that difference can be optimised out by the compiler/OpCache: detect clones that immediately replace their original, and optimise it to an in-place modification. In other words, compile $foo = clone $foo with { x: 42 } to $foo->x = 42, even if the clone is actually in a "withX" method.

-Mike

---

## #112696 — Rowan Tommins — 2020-12-31T12:37:29+00:00

URL: https://externals.io/message/112627#112696 · In reply to: #112691

Hi Mike and Olle,



> A different perspective is that "withX" methods require a mental translation where "addX" methods do not, much like how a person whose native language is English will find it a challenge to (or cannot) "think" in French.


I wonder if that's just about the choice of names, rather than the 
mutability/immutability itself?


> > […]
> Ignoring that you are comparing apples and oranges (scalars to objects,) the latter is easier to reason about IMO.


Ignoring the distinction between "scalar" and "object" was kind of the 
point: they are both "values", and are more naturally treated the same 
as differently.


To take a different example, consider writing a new number type (for 
arbitrary precision, or complex numbers, or whatever), with an "add" method.

The mutable version looks something like this:

public function add($other) {
     $this->value = $this->value + $other;
}

and has to be used like this:

$start = new MyNumber(1);
$end = clone $start;
$end->add(5);


The immutable version might look more like this:

public function add($other) {
     return clone $this with { value: $this->value + $other };
}

and is used like this:

$start = new MyNumber(1);
$end = $start->add(5);

That's much closer to the "$end = $start + 5;" we're used to.



> > […]
> Using a variable on right-hand side does not automatically create an
> alias, so in the above case you don't have to use clone.


Whether or not the type system forced you to, you'd have to use clone if 
the values were implemented as mutable. Switching to methods again may 
make that clearer:

$c = new MyNumber(299_792_458);
$m = new MyNumber(10);
$e = $m->multiply( $c->square() );

If multiply() and square() are mutating state, rather than returning new 
instances, $c is now 89875517873681764, which is going to totally mess 
up the universe...


Regards,

-- 
Rowan Tommins
[IMSoP]

---

## #112699 — olleharstedt@gmail.com — 2020-12-31T14:04:18+00:00

URL: https://externals.io/message/112627#112699 · In reply to: #112696

2020-12-31 12:37 GMT, Rowan Tommins <rowan.collins@gmail.com>:
> Hi Mike and Olle,
>
>
> 
> > […]
>
>
> I wonder if that's just about the choice of names, rather than the
> mutability/immutability itself?
>
>
> > […]
>
>
> Ignoring the distinction between "scalar" and "object" was kind of the
> point: they are both "values", and are more naturally treated the same
> as differently.
>
>
> To take a different example, consider writing a new number type (for
> arbitrary precision, or complex numbers, or whatever), with an "add"
> method.
>
> The mutable version looks something like this:
>
> public function add($other) {
>      $this->value = $this->value + $other;
> }
>
> and has to be used like this:
>
> $start = new MyNumber(1);
> $end = clone $start;
> $end->add(5);
>
>
> The immutable version might look more like this:
>
> public function add($other) {
>      return clone $this with { value: $this->value + $other };
> }
>
> and is used like this:
>
> $start = new MyNumber(1);
> $end = $start->add(5);
>
> That's much closer to the "$end = $start + 5;" we're used to.
>
>
> 
> > […]
>
>
> Whether or not the type system forced you to, you'd have to use clone if
> the values were implemented as mutable. Switching to methods again may
> make that clearer:
>
> $c = new MyNumber(299_792_458);
> $m = new MyNumber(10);
> $e = $m->multiply( $c->square() );
>
> If multiply() and square() are mutating state, rather than returning new
> instances, $c is now 89875517873681764, which is going to totally mess
> up the universe...
>
>
> Regards,
>
> --
> Rowan Tommins
> [IMSoP]

Yes, of course you can find use-cases where immutability is a better
choice, just like I can find use-cases where (constrained) mutability
is better. The point is not to replace one tool with another, but
rather adding another tool to the toolbox. The web dev discourse is
one-sided with regard to immutability, I think. Wish I had time to
implement a PR to Psalm to show something more concrete... Again, if
you only have a hammer, everything looks like a nail. :)

Olle

---

Next page: https://externals.io/message/112627.md?page=2
