Skip to content

Commit ca920ba

Browse files
authored
Merge pull request #15211 from goelakash/issue-14821
Added performance tip for parentheses in expressions to docs
2 parents ba67d2e + 7a27c60 commit ca920ba

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed

doc/manual/performance-tips.rst

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -947,6 +947,51 @@ Taken to its extreme, pre-allocation can make your code uglier, so
947947
performance measurements and some judgment may be required.
948948

949949

950+
Use parentheses in long arithmetic operations
951+
---------------------------------------------
952+
953+
If your code has a long arithmetic operation involving ``+`` or ``*`` operators,
954+
then consider using parentheses to chain up to four or five operations together.
955+
This is to avoid the splatting penalty from a longer list of arguments to function
956+
return statement.
957+
958+
Without parentheses:
959+
960+
const k = zeros(20)
961+
function test_mem()
962+
return k[1] + k[2] + k[3] + k[4] + k[5] + 2.0 * k[6] + k[7] + k[8] + k[9] + k[10]
963+
end
964+
965+
function test(n::Int64)
966+
ret = 0.0
967+
for i = 1:n
968+
ret += test_mem()
969+
end
970+
ret
971+
end
972+
@time test(100000000)
973+
974+
5.017971 seconds (900.00 M allocations: 13.411 GB, 15.04% gc time)
975+
976+
With:
977+
978+
const k = zeros(20)
979+
function test_mem()
980+
return (k[1] + k[2] + k[3] + k[4] + k[5]) + 2.0 * k[6] + k[7] + k[8] + k[9] + k[10]
981+
end
982+
983+
function test(n::Int64)
984+
ret = 0.0
985+
for i = 1:n
986+
ret += test_mem()
987+
end
988+
ret
989+
end
990+
@time test(100000000)
991+
992+
0.302478 seconds (5.26 k allocations: 248.985 KB)
993+
994+
950995
Avoid string interpolation for I/O
951996
----------------------------------
952997

0 commit comments

Comments
 (0)