Skip to main content
 首页 » 编程设计

Python之我的代码高效吗或者人们会从杀死我的服务器中获得乐趣......

2025年05月04日9飞鱼

好吧,基本上,我有一个看起来像这样的数据库:

id | parentid | type    | name 
--------------------------------------------- 
 1 |   0      | heading | this is my heading 
--------------------------------------------- 
 2 |   1      | child   | this is one of many child elements 

我正在使用 Mako 浏览该数据列表并创建嵌套的 UL。它似乎工作得很好......但我不确定我的代码是否可以改进。

这里是:

<%def name="getCategories(parentID)"> 
 
   ## This function creates the children LI for the main headings 
   ## Parameters: 
   ##    parentID - Integer - ID of the heading you want to get the children for 
 
   <% 
      categories = [x for x in c.headings if x.type == 'category' and x.parentid == parentID] 
      categories.sort(key=lambda x: x.name) 
   %> 
 
   %for category in categories: 
      <li> 
         <ul> 
            <li>${category.name.title()}</li> 
            ${getSubCategories(category.id)} 
         </ul> 
      </li> 
   %endfor 
 
   <%def name="getSubCategories(parentID)"> 
      ## Get the subcategories for the parent category 
      ## 
      ## This could eventually turn into a recursive function to get further subcategories 
      ## which is why it has it's own function rather than just having another for loop above 
      ## 
      ## Parameters: Same as above 
 
      <% 
         categories = [x for x in c.headings if x.type == 'category' and x.parentid == parentID] 
         categories.sort(key=lambda x: x.name) 
      %> 
 
      %for category in categories: 
         <ul> 
            <li>${category.name.title()}</li> 
         </ul> 
      %endfor 
   </%def> 
 
</%def> 

如果您想知道为什么我有两个函数会产生相同的输出,那是因为它们不会。从 getSubCategories() 生成的嵌套 UL 的样式 (HTML) 与从 getCategories() 生成的样式不同。

这很慢吗?它会在重负载下死掉吗?可以改进吗?

非常感谢您的建议。干杯。

请您参考如下方法:

首先,如果不进行测试,就无法知道它是否会在重负载下死机。诚实回答您问题的唯一方法是 profile你的代码。只有你能做到。

现在,嵌套关系总是很慢,但你似乎只使用了 2 层嵌套,因此它是 O(n^2),没有什么可以远程杀死服务器。

一些改进方法:

  • 消除代码和标记之间的这种混合。它真的很难阅读,可能也很难调试。我知道 Mako 足够灵活,可以让你这样做,但这并不是因为你可以,而是你应该这样做。试试看 MVC .
  • 如果它显示自己很慢,则探索替代方案,例如 closure tables .但由于您只是显示树,它可能根本没有影响。您最多可以加快排序速度。
  • 谈到排序,尝试在查询数据库时而不是在代码中对类别进行排序和筛选。做这件事比你强。
  • 或者,如果您不这样做,至少只进行一个循环来生成两个列表。过滤是一样的,不需要遍历所有项目两次。
  • 我想您的类别不会在每次加载页面时都发生变化。缓存它。