dotnet-api-docs icon indicating copy to clipboard operation
dotnet-api-docs copied to clipboard

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

Open christiansblackburn opened this issue 11 months ago • 2 comments

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

christiansblackburn avatar Jan 27 '25 02:01 christiansblackburn

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).

gfoidl avatar Jan 27 '25 15:01 gfoidl

@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.

christiansblackburn avatar Jan 31 '25 06:01 christiansblackburn