Skip to content

feat: add cast() for conditional dtype conversion without unnecessary copy - #26

Merged
CodeWithKyrian merged 1 commit into
mainfrom
feat/add-cast-method
Jun 6, 2026
Merged

CodeWithKyrian merged 1 commit into
mainfrom
feat/add-cast-method

Conversation

@CodeWithKyrian

Copy link
Copy Markdown
Contributor

This PR adds a cast() method that conditionally converts array dtypes, returning the same instance when no conversion is needed.

Motivation and Context

astype() always returns a fresh copy, even when the array is already the target dtype. This is correct NumPy semantics, but it forces unnecessary allocations in callers that just want to ensure a certain dtype without paying for a copy when one isn't needed. Patterns like $arr->astype(DType::Float64) inside hot loops waste memory and time when the array already matches.

What's Changed

  • Added NDArray::cast(DType $dtype): self — returns $this when dtype matches, delegates to astype() when conversion is needed
  • Added cast() global function alias in Functions.php
  • Documented cast() alongside astype() in the data-types and views-vs-copies guide pages, highlighting the semantic difference

Breaking Changes

None.

@CodeWithKyrian
CodeWithKyrian merged commit 82cacb7 into main Jun 6, 2026
14 checks passed
@CodeWithKyrian
CodeWithKyrian deleted the feat/add-cast-method branch June 6, 2026 16:07
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant