6

Whats a more efficient way to do the same thing that the next line of code is doing:

X = ["Please", "Thx", "Hello", "World"]
findfirst(k->occursin('H',k)==true,X)

So basically i'm trying to find the first element of the array X that has the uppercase letter H, so in the example the output is 3, but is there a more efficient way of doing this?

4
  • 5
    This is an efficient code. The only thing is that you could remove == true (but it will not affect the performance). Commented May 8, 2021 at 7:57
  • 5
    you can use contains and make it look a bit nicer : findfirst(contains('H'),X) Commented May 8, 2021 at 12:25
  • If X is a constant or does not change too much at runtime, then you can optimize this a bit (especially if X is bigger in practice). Commented May 9, 2021 at 16:23
  • I guess contains it's faster, based on the answer below, and X it could be bigger, my code finds chemical elements in ecuations, so i have to iterate over 'H' to find diferent elements in the array X (which contains the ecuations). Commented May 9, 2021 at 23:38

1 Answer 1

2

Unless I am missing something fundamental here, check out the timings below:


julia> @time findfirst(k->occursin('H',k),X)
  0.015461 seconds (11.20 k allocations: 689.455 KiB, 99.63% compilation time)
3

julia> @time findfirst(contains('H'),X)
  0.000008 seconds
3

Seems like the contains route is significantly more performant than occursin.

Sign up to request clarification or add additional context in comments.

1 Comment

Testing the occursin and contains functions all alone in the same case gives me that occursin i'ts faster, i guess the improvement in time comes from not having to declare an implicit function to make contains work, just as a fun fact this is, so thanks for answering.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.