Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PHP面试题 #70

Open
1 of 4 tasks
woodongwong opened this issue Sep 26, 2022 · 1 comment
Open
1 of 4 tasks

PHP面试题 #70

woodongwong opened this issue Sep 26, 2022 · 1 comment

Comments

@woodongwong
Copy link
Owner

woodongwong commented Sep 26, 2022

记录自己遇到的面试题,答案是根据自己的经验写的,不保证正确。

PHP 的哪些语言特征在合适的场景中可以显著减少程序的内存开销?

  • A: Trait
  • B: Generator
  • C: SPL
  • D: Type hint

解析

首先排除A和D,D指的是类型声明

Generator在减少内存方面是有争议的,从本质上将,Generator无法减少内存开销,Generator只是通过yield改变了代码执行顺序,目前Generator使用比较广泛的应用就是协程调度,比如amp框架。关于协程调度可以阅读这篇文章:https://www.laruence.com/2015/05/28/3038.html

既然是节省内存开销,肯定是和数据结构有关系,在SPL中有一个SplFixedArray类,当数组比较大时,可以有效的减少内存的占用,具体效果可以看一下php-arrays-in-memory-comparison,SplFixedArray有很多限制,在使用方便程度上,不如Array,具体限制可以查看官方文档

@woodongwong
Copy link
Owner Author

@BadJacky Thanks,我之所以认为 Generator 无法节省内存是从内存的角度出发,在 Generator 的 RFC中,Nikita 写了一个 getLinesFromFile 函数示例,分享了使用 yield 关键字节省了很多代码,并且提升了性能

function getLinesFromFile($fileName) {
    if (!$fileHandle = fopen($fileName, 'r')) {
        return;
    }
 
    while (false !== $line = fgets($fileHandle)) {
        yield $line;
    }
 
    fclose($fileHandle);
}
 
$lines = getLinesFromFile($fileName);
foreach ($lines as $line) {
    // do something with $line
}

其实例子中的节省内存的核心是fgets+while,当然 Generator 可以使程序更简洁高效。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant