Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Một lần nữa, sau khi khởi động lại máy chủ web của chúng tôi và chạy mã mười lần, chúng tôi tính toán thời gian thực hiện trung bình. Sử dụng một vòng lặp trong khi truy cập vào các yếu tố cá nhân của mảng trung bình đã 0,0099 ms. So sánh vòng lặp cuối cùng của chúng tôi là cho vòng lặp. | CHAPTER 3 PHP CODE OPTIMIZATION Once again after restarting our web server and running the code ten times we calculate the average execution time. Using a while loop to access individual elements of the array on average took .0099ms. Our final loop comparison is the for loop. Using the code shown in Listing 3-13 we follow the same process in benchmarking the loop by restarting our web server executing the code ten times and taking the average results. Listing 3-13. Using a for Loop in Listing 3-11 php items array_fill 0 100000 12345678910 start microtime reset items for i 0 i 100000 i . . . j items i . . . . echo microtime - start The results for all three loop benchmarks are shown in Table 3-1. Using the results shown in the table accessing array elements using a foreach loop proves to be the best approach. Table 3-1. PHP Loop Average Execution Times for 100 000-Element Array Loop Type Average Execution Time foreach .0078ms while .0099ms for .0105ms File Access PHP contains four methods to fetch data from a file fread file_get_contents file and readfile . file_get_contents readfile and fread return data as a string while file returns the data within the file as an array where each line within the file is an element in the array. Though all four can read the file contents only file_get_contents places the file in memory for faster read write access called memory mapping. Using memory mapping file_get_contents boosts its performance when reading small files on systems that support it. We will compare both methods fread as well as file_get_contents on two scenarios returning data as a string on a small 3.9KB file and then returning the data from a large 2.3MB file Listing 3-14 . 64 CHAPTER 3 PHP CODE OPTIMIZATION Listing3-14. Fetching Content from a 3.9KB File Using fread Accessing 100000 Times php fileToFetch YOUR_3.9KB_FILE_STORED_LOCALLY Access the file 100000 times start microtime for i 0 i 100000 i . . fileContent file_get_contents fileToFetch end microtime - .