Some attempts at code optimization

Source: Internet
Author: User

1. Loop body

The difference in the two-segment loop body of the following program is only the use of local variables to reduce the one-time addition operation

Func Main () {buf: = make ([]byte, 100000000) var offset intvar sum int//do not use local variables, multiple addition operations T3: = time. Now () offset = 0sum = 0for I: = 0; I < Len (BUF); i++ {sum + = Int (buf[offset+i]) sum + = Int (Buf[offset+i])}t4: = time. Now (). Sub (T3) fmt. PRINTLN (T4)//Use local variable/*t1: = time. Now () offset = 0sum = 0for I: = 0; I < Len (BUF); i++ {Temp: = offset + isum + = Int (buf[temp]) sum + = Int (buf[temp])}t2: = time. Now (). Sub (t1) fmt. Println (T2) */return}

Results of multiple runs: the first paragraph (unused local variables) is always 7% or so slower than the second paragraph. The number of cycles in the experiment must be large enough (10^8 or more), otherwise the result is uncertain

Conclusion: In the case of a large number of cycles, local variables can reduce the running time.

2. The effect of type conversion on run time

The only difference between the two test programs is whether the type conversion is done

Result: The running time of the two is basically consistent

Conclusion: type conversion has little effect on program operation.

  

  

Some attempts at code optimization

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.