DEV Community

Discussion on: Benchmarked new perl class feature with many class builders[2024-06-10 updated]

Collapse
 
leonerd profile image
Paul Evans

Something to keep in mind with the field access benchmarks is that the very design of Object::Pad and the core class system offers direct access to the fields of the object to the class's own methods, as simple lexicals. Code inside methods does not have to use the accessors just to see or modify those values. This is a feature unique to those two systems.

Therefore, in real-world code scenarios, the faster more-direct access these provide means that overall code can run faster in a way that simple benchmarks "from outside the class" such as your bench-field.pl do not manage to capture. It would not be easily possible to write a "universal" test case in the same style as your scripts to demonstrate this, exactly because of this unique ability.

As an example, consider this silly class:

class RGBColour {
  field $red :param;
  field $green :param;
  field $blue :param;

  method as_css () {
    sprintf "rgb(%f%%,%f%%,%f%%)", $red, $green, $blue;
  }
}
Enter fullscreen mode Exit fullscreen mode

The ->as_css method here has direct access to the $red, $green and $blue lexicals, and so invoking that would only involve one actual method call at runtime. Whereas, this class based on any of the other systems would need code something like:

sub as_css ($self) {
  sprintf ..., $self->red, $self->green, $self->blue;
}
Enter fullscreen mode Exit fullscreen mode

and thus any call to the outer method would involve three inner calls, a total of four. Once you get into real-world scenarios with code that contains real-world behaviour, the cost of all these little inner $self->field accessor calls quickly adds up and overtakes the original cost of the outside method call or even the object constructor.

Perhaps you could add a new category of benchmark, one that constructs an object with a few nontrivial fields and then performs a calculation method based on the values of those fields - feel free to steal my example code above if it helps. I'd be very interested to see benchmarks of that kind of case too.

Collapse
 
kfly8 profile image
kobaken

Thanks for your kind comments!

I will try the new benchmark case!