Skip to content

Add a method to String that returns the first character #7830

Open
@wooster0

Description

I think a method should be added to String that returns the first character and should be a faster alternative to [0]. The strategy is to start an iteration through the string but stop at the first character. That's faster than [0]. Reason for this is for example the each_byte on ASCII-only optimization in String#each_char.

require "benchmark"

Benchmark.ips do |bm|
  bm.report "each_char" do
    "hello".each_char do |char|
      break char
    end
  end

  bm.report "[0]" do
    "hello"[0]
  end
end
each_char 394.43M (  2.54ns) (± 5.82%)  0.0B/op        fastest
      [0] 196.71M (  5.08ns) (± 5.03%)  0.0B/op   2.01× slower

The first is also faster for non-ASCII characters.
This optimization is for example already used here: string.cr:4069.
The method could perhaps be called first or first_char.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions