Skip to content

Cop idea: prefer String#bytesize over String#bytes#size #475

@viralpraxis

Description

@viralpraxis

I've seen some developers using some_string.bytes.size (or count/length) instead of the constant-time String#bytesize method.

In MRI there is no copy-on-write optimization for string/array conversion, so for large strings, the unnecessary array allocation could result in performance issues

require "objspace"

s = "a" * 1_000_000
initial = ObjectSpace.count_objects_size[:T_ARRAY]
b = s.bytes.count
p (ObjectSpace.count_objects_size[:T_ARRAY] - initial) / (1 << 10)

> 7812

I've opened #474 which will be finished if the idea accepted

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions