<div dir="ltr">ok, I understand hashes might not be the best.<div><br></div><div>I agree that the StringSwitch is concise and easy to read, but aren't we doing a bunch of extra work even if a match is found in the very first case, while in the if we would early exit.</div><div><br></div><div>Anupama</div></div><div class="gmail_extra"><br><div class="gmail_quote">On Fri, Feb 5, 2016 at 4:42 PM, Mehdi Amini <span dir="ltr"><<a href="mailto:mehdi.amini@apple.com" target="_blank">mehdi.amini@apple.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><span class=""><br>
> On Feb 5, 2016, at 2:43 PM, Anupama Chandrasekhar via llvm-dev <<a href="mailto:llvm-dev@lists.llvm.org">llvm-dev@lists.llvm.org</a>> wrote:<br>
><br>
> Hi:<br>
><br>
> I have a question about the llvm StringSwitch class. Why is this more efficient than comparing the hashes of the strings or just using a bunch of if statements.<br>
<br>
</span>I don't know about hashes performance (comparing a small string is probably more efficient than comparing hashes, and I'd be reluctant to collisions anyway). Now since you mentioned a "bunch of if statements" you can get very close.<br>
StringSwitch is caching the length of the string to compare and first checking the length before doing the actual comparison using memcmp. So the two constructs below it should be equivalent:<br>
<br>
int i = StringSwitch<int>("abc").case("de", 1).case("fghi", 2).case("jkl", 3).default(-1);<br>
<br>
and:<br>
<br>
int i;<br>
const char *str = "abc";<br>
int len = strlen(str);<br>
if(len == 2 && std::memcmp(str, "de", 2) {<br>
i = 1;<br>
} else if(len == 4 && std::memcmp(str, "fghi", 4) {<br>
i = 2;<br>
} else if(len == 3 && std::memcmp(str, "jkl", 3) {<br>
i = 3;<br>
} else {<br>
i = -1<br>
}<br>
<br>
<br>
I left up to you to appreciate the readability :)<br>
<span class="HOEnZb"><font color="#888888"><br>
--<br>
Mehdi<br>
<br>
<br>
</font></span></blockquote></div><br></div>