简体   繁体   中英

OO performance question

I will be quick and simple on this. Basically I need to merge multiple Invoices(Object) quickly and fast.

A simple idea is to

$invoice1 = new Invoice(1);
$invoice2 = new Invoice(2);
$invoice3 = new Invoice(3);
$invoice1->merge($invoice2,invoice3);
$invoice1->save();

Since each object will query it's own data, the number of queries increase as the number of invoices needed to be merge increases.

However, this is a case where a single query

SELECT * FROM invoice WHERE id IN (1,2,3)

Will suffice, however the implementation will not be as elegant as the above.

Initial benchmarks on sample data indicates a 2.5x-3x decrease in speed on the above due to the sheer number of mysql queries.

Advice please

Use an Invoice factory. You ask it for invoices using various methods. newest(n) get(id) get(array(id,id,id)) so on, and it returns arrays of invoices or single invoice objects.

<?php
    $invoice56 = InvoiceFactory::Get(56); // Get's invoice 56
    $invoices = InvoiceFactory::Newest(25); // Get's an array of the newest 25 invoices
?>

你能使Invoice对象变得懒惰,让merge加载尚未加载的所有内容吗?

Make sure you work on the same db connection all the time. Check that it does not reconnect in one script execution thread.

I could suggest looking into using an actual ORM (object relational mapping) in order to create a seperation between your actual queries and the objects used.. Take a look at Propel or (my favorite) Doctrine (version 2 is very easy to use)

That way you could have exactly what you want in just the same amount of code...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM