I was writing some Rust code to parse time data, and partway through I noticed the value had an extra ' around it that needed to be stripped. I wrote the comment on line 242 so Copilot would get to work, and it suggested line 243. That’s correct, but the more correct and more sensible solution is the one I wrote on line 244.

Editor screenshot of the Rust code: line 242 is a comment asking to trim extra quotes, line 243 is Copilot’s suggestion, which trims a single-quote string pattern with trim_start_matches and trim_end_matches, and line 244 is my version, which trims a single-quote char pattern instead

For the uninitiated:

  • Line 243 says: if there’s a string ' at the start or end of the date string, remove it.
  • Line 244 says: if there’s a character ' at the start or end of the date string, remove it.

For the initiated:

  1. Both &str and char implement the Pattern Trait in Rust, which is why both versions work.

    Editor hover documentation for trim_start_matches, showing that its pat argument can be any type that implements core::str::pattern::Pattern

  2. In Copilot’s version, two static strings get allocated in .data, and for them two fat pointers get built on the function’s stack when line 243 runs. In my version, on the other hand, just two bytes’ worth of numbers get hardcoded, and there’s no extra storage involved.

  3. Even though &str and char both implement Pattern, their implementations are different.

    In the &str implementation, where you’re effectively comparing two strings, it first checks that the needle isn’t the empty string, and then the lengths of the two strings are compared. Only if the needle is shorter than the haystack does it then check whether the needle’s length is one, in which case only the first byte is examined.

    In contrast, the char implementation skips all of that and checks the first byte directly. In effect, the char implementation is two branches faster!

    Of course, premature optimization is for the short-sighted, and the compiler and the CPU back there will probably put us in our place anyway!

  4. I was wondering why Copilot would suggest something like this in the first place, and two reasons came to mind:

    1. People are genuinely lazy, and typing "'" is easier for them than '\'' because it’s one character shorter!
    2. Python! I feel like I read somewhere that in Python, using ' ' for strings is frowned upon and people are advised to always use " ". And since GitHub is full of Python code, Copilot basically starts all its string-related suggestions with " instead of '.