-1

我在数据库中有一个名为 ads 的表,该表包含有关每个广告的数据。我想从表格中获取该数据以显示广告。

现在,我有两个选择:

  1. 要么从表中获取所有数据并将其存储在数组中,然后,我将使用此数组处理以在其位置显示每个广告by using loops
  2. 或者直接访问表并获取每个广告数据以显示它,注意这种方式会消耗更多对数据库的查询。

哪一个是最好的方法,而不是让脚本更慢?

4

4 回答 4

0

In most Cases #1 is better.

Because, if you can select the data (smallest, needed set) in one query, then you have less roundtrips to the database server.

Accessing Array or Objectproperties (from Memory) are usually faster than DB Queries. You could also consider to prepare your Data and don't mix fetching with view output.

The second Option "select on demand" could make sense if you need to "lazy load", maybe because you can or want to recognize client properties, like viewport.

于 2012-10-01T13:13:34.040 回答
0

You should always try to run a PHP script with the least amount of database queries possible. Whenever you query the database, a request must be sent to the database (usually) over the network, and your script will idle until the request came back.

You should, however, make sure not to request any more data from the database than necessary. So try to filter as much in the WHERE clause as possible instead of requesting the whole table and then picking individual rows on the PHP layer.

We could help with writing that SQL query when you tell us how your table looks and how you want to select which ads to display.

于 2012-10-01T13:13:44.540 回答
0

我想强调以下部分:

从表中获取所有数据并将其存储在数组中

您不需要将所有行存储到数组中。您还可以采用一个表示结果集的迭代器,然后使用该迭代器。

根据您使用的数据库对象,这通常是内存占用较少的变体。此外,您将在此处只运行一个查询,这是更可取的。

迭代器实际上在现代数据库结果对象中很常见。

此外,这有助于将视图代码与实际的数据库交互分离,您也可以推迟执行 SQL 查询。

于 2012-10-01T13:12:18.813 回答
0

您应该尽量减少查询量,但也应该尽量减少实际从数据库中获取的数据量。

所以:只获取您实际展示的那些广告。例如,您可以使用columnPK IN (1, 2, 3, 4)来获取这些广告。

一个值得注意的例外:如果您的应用程序以“广告”为中心,并且您几乎在任何地方都需要它们,和/或它们不会消耗太多内存,和/或没有太多添加,那么在性能方面可能会更好将所有(或部分)广告存储在一个数组中。

最重要的是:Measure, measure, measure

很难预测哪种算法最有效。通常,您实施某些“因为它会更有效”只是后来才发现您的优化实际上正在减慢您的应用程序。

于 2012-10-01T13:12:47.380 回答