Overview
| Artifact ID: | ce1ee311fe82c638ac6de88242d6133131e7a00c |
|---|---|
| Ticket: | 2958832fffffffffffffffffffffffffffffffff
Further speed-up of ouster-hash function |
| User & Date: | dkf on 2016-08-23 13:45:21 |
Changes
- assignee changed to: "aku"
- closedate changed to: "2457624.07316888"
- closer changed to: "dkf"
- comment changed to:
The ouster-hash function (HashStringKey in tclHash.c, and two variants in other places) can be speed up further. Here is my suggestion, which is 5 assembler instructions faster for every function call. For an explanation, see below (read on). ================ new ==================== if ((result = UCHAR(*string)) != 0) { while ((c = *++string) != 0) { result += (result << 3) + UCHAR(c); } } return result; ================ old ===================== for (; (c=*string++) != 0 ;) { result += (result<<3) + UCHAR(c); } return result; =========================================== There is no difference in using a for loop and a while loop. It's exactly the same, apart from personal preference... The first loop entry, result starts being 0, we will shift the 0 value 3 bits, resulting in 0. Then we are adding 0 to UCHAR(c), resulting in UCHAR(c). The question is, when we already know that the result after the first shift and addition will be UCHAR(c), why do we do the shift and the addition at all? In the last loop entry, the pointer is incremented, but the incremented pointer is not accessed any more. So, a little re-ordering could prevent this increment. That's how I came up with the faster code above. How much faster is it? Here is the generated i86 assembler code for both versions, using gcc-4.4. ================ new ==================== HashStringKey: pushl%ebp movl%esp, %ebp movl12(%ebp), %edx movzbl(%edx), %eax testl%eax, %eax je.L32 leal1(%edx), %ecx movzbl1(%edx), %edx testb%dl, %dl je.L32 .L35: movzbl%dl, %edx addl$1, %ecx leal(%edx,%eax,8), %edx addl%edx, %eax movzbl(%ecx), %edx testb%dl, %dl jne.L35 .L32: popl%ebp ret ================ old ===================== HashStringKey: pushl%ebp xorl%eax, %eax movl%esp, %ebp movl12(%ebp), %ecx movzbl(%ecx), %edx testb%dl, %dl je.L33 addl$1, %ecx .L34: movzbl%dl, %edx leal(%edx,%eax,8), %edx addl%edx, %eax movzbl(%ecx), %edx addl$1, %ecx testb%dl, %dl jne.L34 .L33: popl%ebp ret =========================================== Zo, the main loop has 7 instructions, only in a different order. The preparation has 10 instructions, against 8 before, but the loop has to be run one less time! So, we gain 5 instructions! Using another processor, the result will be different, but fact is that we save a shift, an addition and an increment. Anyone, who can do better? - login: "dkf"
- mimetype: "text/plain"
- severity changed to: "Minor"
- subsystem changed to: "11. Conversions from String"