使用提取方法优化laravel项目

时间:2018-08-13 03:07:19

标签: php laravel optimization laravel-5.1

我正在进行一个正在进行的使用laravel 5.1的laravel项目。整个过程需要8秒钟以上。在此过程中,有一个方法将包含近250行代码。从优化角度来看,如果我将代码提取为几种方法,它会比平时更快还是会花费很多时间?

2 个答案:

答案 0 :(得分:1)

将一个大功能分解为多个小功能不会更快,相反,由于调用多个功能,它会变得更慢。

我建议更改您的方法,将队列用于异步进程,等等。

答案 1 :(得分:1)

使用PHP,通常可以做一些事情来加速代码:

尽可能使用参考。

默认情况下,每当您调用带有参数的函数时,都会创建变量的副本。如果经常调用将数组或字符串作为参数的函数,那么这可能会非常昂贵。因此,不要做类似的事情:

import pygame
import sys

# Define some colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)

pygame.init()

# Set the height and width of the screen
size = [800, 600 ]
screen = pygame.display.set_mode(size)

pygame.display.set_caption("Basketball Shootout")

# Loop until the user clicks the close button.
done = False

# Used to manage how fast the screen updates
clock = pygame.time.Clock()

#Rectangles
rect1 = pygame.Rect(300,300,205,80)
rect2 = pygame.Rect(300,400,205,80)

#Font
font3 = pygame.font.Font("Minecraft.ttf", 40)

def playerpong():
    import playerpong



while not done: 
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True


        screen.fill(BLACK)

        pygame.draw.rect(screen, GREEN, rect1)
        pygame.draw.rect(screen, RED, rect2)


        if event.type == pygame.MOUSEBUTTONDOWN:
            if event.button == 1:
                if rect1.collidepoint(event.pos):
                    playerpong()
                if rect2.collidepoint(event.pos):
                    pygame.quit()

        clock.tick(60)

        pygame.display.update()

pygame.quit()

使用:

function f($array) {

这意味着对function f(&$array) { 的任何修改也会影响原始数组,因此仅应在$array没有被修改或您不在乎被修改的情况下使用它。

对于$array循环同样如此。只需确保在完成循环后foreach变量即可避免问题。

unset()

另一个技巧是预先分配缓冲区,而不是让它们自动扩展。例如,代替:

foreach ($set as &$element) { ... }
unset($element);

您确保$numbers = [1, 2, 3, 4, ... 10000000]; $inverted = []; foreach ($numbers as $num) { $inverted[] = 1 / $num; } 已经具有适合所有元素的大小:

$inverted

同样,尽可能避免调整字符串和数组的大小。处理索引等。

正则表达式虽然方便,但却是性能的大敌。避免将它们用于简单任务。

当然,考虑问题的所有方面都与PHP代码有关。也许不是。如果使用数据库,则可能需要重新评估如何执行SQL查询。您构建它们的方式会严重影响性能。