字符串连接VS在PHP数组破灭 [英] String concatenation vs array implode in PHP

查看:129
本文介绍了字符串连接VS在PHP数组破灭的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

曾使用Java的很长一段时间我的一块创建长串片标准方法是将元素添加到数组,然后破灭的阵列。

Having used Java for a long time my standard method for creating long strings piece by piece was to add the elements to an array and then implode the array.

$out[] = 'a';
$out[] = 'b';
echo implode('', $out);

但后来有很多的数据。

But then with a lot of data.

的(标准PHP)的选择是使用字符串连接。

The (standard PHP) alternative is to use string concatenation.

$out = 'a';
$out .= 'b';
echo $out;

要我惊讶的是似乎有两种方法之间没有速度差。当有显著时差通常它是似乎更快的串联,但不是所有的时间

To my surprise there seems to be no speed difference between both methods. When there is significant time difference usually it is the concatenation that seems faster, but not all of the time.

所以我的问题是:有没有 - 除了风格和code可读性 - 任何其他理由选择了另一种方法

So my question is: are there - apart from style and code readability - any other reasons to choose one approach over the other?

推荐答案

在我看来,使用数组意味着你会做一些事情,不能用简单的字符串连接来完成。排序一样,检查是否有独特性,等等。如果你没有做这样的事情,那么字符串连接会更容易被人谁不知道code在一两年来读取。他们不会有怀疑阵列是否会内爆之前被操纵。

To me, using an array implies that you're going to do something that can't be done with simple string concatenation. Like sorting, checking for uniqueness, etc. If you're not doing anything like that, then string concatenation will be easier to read in a year or two by someone who doesn't know the code. They won't have to wonder whether the array is going to be manipulated before imploded.

这是说,我走内爆阵列的方法,当我需要建立用逗号或和串词与词之间。

That said, I take the imploded array approach when I need to build up a string with commas or " and " between words.

这篇关于字符串连接VS在PHP数组破灭的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆