if ((stringValue.IndexOf("pink") > -1)) is inefficient
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
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 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.