php - 什么更好?在foreach中调用函数还是在函数中调用foreach?
问题描述
我正在尝试改进我的代码,现在我想知道什么更好(性能和代码风格):
public function xxx() {
...
foreach ($customers as $customer) {
$this->createCustomer($customer);
}
...
}
public function createCustomer($customer) {
// Create customer
}
或者
public function xxx() {
...
$this->createCustomers($customers);
...
}
public function createCustomers($customers) {
foreach ($customers as $customer) {
// Create customer
}
}
谢谢!
解决方案
这里有更好的版本
public function xxx() {
...
$ToBeCreatedCustomers = validateAndFormatCustomers($customers)
Customer::insert($ToBeCreatedCustomers);
...
}
public function validateAndFormatCustomers() {
$ToBeCreatedCustomers = []
foreach ($customers as $customer) {
$ToBeCreatedCustomers[] = [
'name' => $customer['name'],
.....
]
}
return $ToBeCreatedCustomers;
}
推荐阅读
- java - 为什么 List.contains(Object) 的行为不同?
- r - 如何在同一个数据帧上做colsum和average
- powerbi - 使用 DAX 生成日期系列
- javascript - 仅在服务器上需要一个包
- java - Intellij IDEA 仅针对所有未提交的更改运行测试
- regex - 在换行符之前匹配字符,不包括空格?
- macos - MacOS - 使用带有launchd的脚本 - 启动,登录,注销,关闭?
- service-worker - Workbox 的服务人员在更改时未更新
- python - AllenNLP 共指分辨率的多 GPU 训练
- reactjs - 事件处理程序中带有 [name] 的 PrevState