hhvmhacklang

Most efficient way to print variable number of characters in Hack?


I'm working on a Hack project and I've come across a situation where I need to print $n spaces. Here's how I'm currently doing it:

for ($i = 0; $i < $n; $i++) echo " ";

I'm wondering whether $n calls to echo is the most efficient way to go about this? From a little bit of googling, I learned that generally, multiple calls to echo are faster than string concatenation and that Hack doesn't have a built in StringBuilder equivalent. Does my for loop achieve that maximum efficiency or is there something else I'm missing?

Thanks!


Solution

  • If you are using HackLang, you should use HSL ( Hack standard library ) instead of legacy php functions.

    The best way to go around this is to use Str\repeat function ( similar behavior as str_repeat in PHP )

    use namespace HH\Lib\Str;
    
    echo Str\repeat(' ', $n);
    

    Note: make sure to use the same HSL version as HHVM

    if you are using HHVM 4 ( recommended ), do composer require hhvm/hsl:^4

    if you are using HHVM 3, do hhvm $(which composer) require hhvm/hsl:^3

    etc...