in reply to programming languages and immutable data types

Hmm can you plz show me the practical difference to perl?

lanx@nc10-ubuntu:~$ python Python 2.5.2 (r252:60911, Jan 20 2010, 23:16:55) ... >>> str="123" >>> str+="4" >>> str '1234'

The only thing I can think of are runtime issues :

I've read that in JS  str+="a";str+="b" takes 40% longer than str=str+"a"+"b", because strings have to be copied...

But in perl the second version needs much longer...

DB<1> $str="";$t=time;for (1..100000) {$str=$str."a"."b"};print time +-$t 13 DB<2> $str="";$t=time;for (1..1000000) {$str.="a";$str.="b"};print t +ime-$t 1

Actually the same code in python has similar benchmarks

>>> for i in range(1, 1000000): ... str+="a"+"b" ... >>> str="" >>> for i in range(1, 100000): ... str=str+"a"+"b" ...

So where is the practical difference?

Cheers Rolf

UPDATE: Maybe not a good benchmark, since the growing of $str plays a too important role ...

DB<1> $t=time;for (1..10000000) {$str="";$str.="a"."b";};print time- +$t 10 DB<2> $t=time;for (1..10000000) {$str="";$str=$str."a";$str.="b";};p +rint time-$t 17 DB<3> $t=time;for (1..10000000) {$str="";$str=$str."a"."b";};print t +ime-$t 15

Replies are listed 'Best First'.
Re^2: programming languages and immutable data types
by BrowserUk (Patriarch) on May 03, 2010 at 22:55 UTC

    There are other ways of mutating a string than just appending to the end. For example:

    $n=1e3; cmpthese -1,{ a=>q[ my$s = chr(0)x$n; for my $i ( 0..length($s)-1){ substr $s, $i, 1, chr(1); } ], b=>q[ my$s = chr(0)x$n; for my $i ( 0..length($s)-1){ $s = substr($s,0,$i-1) . chr(1) . substr $s,$i+1; } ] };; Rate b a b 811/s -- -85% a 5525/s 581% -- $n=1e4; cmpthese -1,{ a=>q[ my$s = chr(0)x$n; for my $i ( 0..length($s)-1){ substr $s, $i, 1, chr(1); } ], b=>q[ my$s = chr(0)x$n; for my $i ( 0..length($s)-1){ $s = substr($s,0,$i-1) . chr(1) . substr $s,$i+1; } ] };; Rate b a b 13.0/s -- -98% a 556/s 4173% -- $n=1e5; cmpthese -1,{ a=>q[ my$s = chr(0)x$n; for my $i ( 0..length($s)-1){ substr $s, $i, 1, chr(1); } ], b=>q[ my$s = chr(0)x$n; for my $i ( 0..length($s)-1){ $s = substr($s,0,$i-1) . chr(1) . substr $s,$i+1; } ] };; (warning: too few iterations for a reliable count) s/iter b a b 12.5 -- -100% a 1.77e-002 70277% --

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.