Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

if ((stringValue.IndexOf("pink") > -1)) is inefficient #10880

Open
christiansblackburn opened this issue Jan 27, 2025 · 2 comments
Open

if ((stringValue.IndexOf("pink") > -1)) is inefficient #10880

christiansblackburn opened this issue Jan 27, 2025 · 2 comments
Labels
area-WinForms Issues or PRs that relate to WinForms. untriaged New issue has not been triaged by the area owner

Comments

@christiansblackburn
Copy link

Type of issue

Typo

Description

The code example shouldn't read:
if ((stringValue.IndexOf("pink") > -1))

This is more efficient:
if ((stringValue.IndexOf("pink") != -1))

Page URL

https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.datagridview.cellformatting?view=windowsdesktop-9.0&redirectedfrom=MSDN

Content source URL

https://github.com/dotnet/dotnet-api-docs/blob/main/xml/System.Windows.Forms/DataGridView.xml

Document Version Independent Id

d789c17f-da81-5aca-c7f2-63c547287417

Article author

@dotnet-bot

@dotnet-policy-service dotnet-policy-service bot added the untriaged New issue has not been triaged by the area owner label Jan 27, 2025
@dotnet-issue-labeler dotnet-issue-labeler bot added the area-WinForms Issues or PRs that relate to WinForms. label Jan 27, 2025
@gfoidl
Copy link
Member

gfoidl commented Jan 27, 2025

This is more efficient:

Even better is a comparison with 0, so >= 0, as the cpu can fuse the comparison and the jump to only one instruction actually executed.

Code-wise better is to use the string.Contains method, as this is what should be done, and the actual implementation is a detail of .NET (but it's the same as IndexOf and >= 0 comparison).

@christiansblackburn
Copy link
Author

@gfoidl I think contains() sounds fine. However, your suggestion to compare with 0 doesn't make sense because 0 is the index of the first possible found position. Not found has an index of -1. Under no circumstances is >= efficient. That's two operations: is it equal and then is it greater than. Testing for inequality is a single operation. != -1 means it was found because literally any other index is a valid position.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
area-WinForms Issues or PRs that relate to WinForms. untriaged New issue has not been triaged by the area owner
Projects
None yet
Development

No branches or pull requests

2 participants