-4

Sample input

4
abcd
azazaz
abbzbba
flkjdh

Sample output

4
21
22
0

Program in C++:

#define ll long long
char s[1000010];

int main()
{
    int t;
    cin>>t;
    char x;
    scanf("%c",&x);
    while(t--)
    {
        scanf("%s",s);
        int l=-1;
        int len=strlen(&s[0]);
        ll ans=0;

        for(int i=0;s[i]!='\0';i++)
        {
            if(s[i]=='a' || s[i]=='z')
            {
                ans+=((i-l)*(len-i));
                l=i;
            }
        }

        cout<<ans<<endl;
    }
}

Program in Ruby:

n = gets.chomp.to_i

ans = []

for x in 0..n-1
  str1 = gets.chomp
  l = str1.size
  count = 0
  i = 0
  le = -1

  str1.each_char do |cha|
    if(cha == 'a' || cha == 'z')
      count += (i-le)*(l-i)
      le = i
    end
    i += 1
  end
  ans[x] = count
end

puts ans

When considering longer strings, Ruby is 15 times slower than C++. Why?

Mike Zboray
  • 39,828
  • 3
  • 90
  • 122
Starter
  • 45
  • 3
  • 5
    You're comparing Ruby with C++ and then wondering why Ruby is slow? It is not Ruby's fault. It is all your fault that you're comparing in the first place. It is insulting to both languages. – Nawaz Sep 29 '13 at 03:56
  • BTW, C++ will be even more faster if you use `\n` instead of `endl` and disable the syncing C++ IOStreams with C IOStreams. [See my answer here for detailed explanation](http://stackoverflow.com/a/17940337/415784) as to how to make C++ even more faster (compared to whatever language you use). – Nawaz Sep 29 '13 at 03:59
  • 5
    as @Nawaz says, don't get upset at a screwdriver from not being a hammer, and the other way around. – Renaissance Sep 29 '13 at 03:59

1 Answers1

2

The C++ and Ruby programs are not the same. The C++ program uses a char buffer for input - it "recycles" memory - while the Ruby program uses gets, which allocates new memory each time, which takes a toll on performance.

Also, the Ruby program uses an array to store the answer - and that array is being resized all the time! The C++ uses a single answer variable which it prints on each iteration - which is much faster.

Even if you change the programs to eliminate these two differences, the Ruby program will still be slower - but probably not by that much.

Idan Arye
  • 12,402
  • 5
  • 49
  • 68